[프로그래머스] 연속된 부분 수열의 합

박형진·2023년 4월 7일
0

https://school.programmers.co.kr/learn/courses/30/lessons/178870


1. 코드

def solution(s, k):
    answer = []
    total = 0

    start = 0
    for end in range(1, len(s) + 1):
        total += s[end - 1]
        if total > k:
            while total > k:
                print('     ', start, end - 1, total)
                total -= s[start]
                start += 1

        if total == k:
            length = end - 1 - start
            answer.append((length, start, end - 1))
        print(start, end - 1, total)

    return list(sorted(answer)[0][1:])

2. 후기

solution([1, 2, 3, 4, 5], 7)
output)
0 0 1
0 1 3
0 2 6
      0 3 10
      1 3 9
2 3 7
      2 4 12
      3 4 9
4 4 5
solution([1, 2, 3, 7, 5], 7)
output)
0 0 1
0 1 3
0 2 6
      0 3 13
      1 3 12
      2 3 10
3 3 7
      3 4 12
4 4 5
profile
안녕하세요!

0개의 댓글