반응형
Notice
Recent Posts
Recent Comments
Link
동캄의 코딩도장
프로그래머스 level2 [연속된 부분 수열의 합] 파이썬 본문
반응형
https://school.programmers.co.kr/learn/courses/30/lessons/178870
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
# 프로그래머스 level2 연속된 부분 수열의 합
def solution(sequence, k):
answer = []
start=0
end=0
temp=0
while end<len(sequence):
if temp<k: #현재 값이 k보다 작으면
temp+=sequence[end] #맨 끝 값을 하나 더함
end+=1
elif temp==k: # 현재 값이 k와 같으면
answer.append((start,end-1)) # start부터 end-1 까지 더하였으므로, answer에 (start,end-1) 추가
temp-=sequence[start] # 맨 앞의 값을 하나 뺌
start+=1
elif temp>k: #현재 값이 k보다 크면
temp-=sequence[start] # 맨 앞의 값을 하나 뺌
start+=1
while start<end: # 마지막으로 start가 end보다 작을 때
if temp>k: # 현재 값이 k보다 크면
temp-=sequence[start]
start+=1
elif temp==k: #현재 값이 k와 같으면
answer.append((start,end-1))
break
else: #현재 값이 k 보다 작으면
break
answer.sort(key=lambda x:(x[1]-x[0])) # 길이 짧은 순으로 정렬
return answer[0]
반응형
'코테 > 프로그래머스' 카테고리의 다른 글
프로그래머스 level2 [순위 검색] 파이썬 (0) | 2023.04.17 |
---|---|
프로그래머스 level2 [디펜스 게임] 파이썬 (0) | 2023.04.16 |
프로그래머스 level2 [시소 짝꿍] 파이썬 (0) | 2023.04.14 |
프로그래머스 level2 [요격 시스템] 파이썬 (0) | 2023.04.14 |
프로그래머스 level2 [마법의 엘리베이터] 파이썬 (0) | 2023.04.13 |