-
프로그래머스 / 연속된 부분 수열의 합코딩 테스트/Level 2 2023. 4. 11. 23:29반응형
https://school.programmers.co.kr/learn/courses/30/lessons/178870
파이썬
이렇게 쉽게는 넘어가지 않겠지..
def solution(sequence, k): answer = [] for i in range(len(sequence)): for j in range(i + 1, len(sequence) + 1): s = sum(sequence[i:j]) if s == k: answer.append([i, j - 1]) elif s > k: break return sorted(answer, key=lambda x: x[1] - x[0])[0]
소티드를 이용해서 간결하게..
def solution(sequence, k): answer = [] left = right = 0 total = sequence[0] while left < len(sequence) and right < len(sequence): if total == k: answer.append([left, right]) total -= sequence[left] left += 1 elif total > k: total -= sequence[left] left += 1 else: right += 1 if right < len(sequence): total += sequence[right] return sorted(answer, key=lambda x: x[1] - x[0])[0]
소티드를 이용하지 않고 중간에 처리..
def solution(sequence, k): answer = (0, 0, float('inf')) left = right = 0 total = sequence[0] while left < len(sequence) and right < len(sequence): if total == k: if answer[2] > (temp := right - left): answer = (left, right, temp) total -= sequence[left] left += 1 elif total > k: total -= sequence[left] left += 1 else: right += 1 if right < len(sequence): total += sequence[right] return answer[:2]
반응형