반응형
https://programmers.co.kr/learn/courses/30/lessons/49995
코딩테스트 연습 - 쿠키 구입 | 프로그래머스
과자를 바구니 단위로 파는 가게가 있습니다. 이 가게는 1번부터 N번까지 차례로 번호가 붙은 바구니 N개가 일렬로 나열해 놨습니다. 철수는 두 아들에게 줄 과자를 사려합니다. 첫째 아들에게는 l번 바구니부터 m번 바구니까지, 둘째 아들에게는 m+1번 바구니부터 r번 바구니까지를 주려합니다. 단, 두 아들이 받을 과자 수는 같아야 합니다(1 <= l <= m, m+1 <= r <= N). 즉, A[i] 를 i번 바구니에 들어있는 과자 수라고 했을 때, A[
programmers.co.kr

조건에 맞게 분기점을 세우고 접근해야 하는 문제.
정답을 알면 쉽게 코드가 보이지만, 정답에 접근하기까지가 정말 어려웠었다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def solution(cookie): | |
max_value = 0 | |
for i in range(len(cookie)-1): | |
# 분기점을 만들 수 있는 모든 경우의 수를 확인한다. | |
# 맨 뒤에서부터, 앞부분의 합을 front / 뒷부분의 합을 end로 정의한다. | |
front_value, front_idx = cookie[i], i | |
end_value, end_idx = cookie[i+1], i+1 | |
while True: | |
# 앞부분의 합 == 뒷부분의 합, 이전의 max 값보다 클 경우 max_value 업데이트 | |
if front_value == end_value and front_value > max_value: | |
max_value = front_value | |
# 앞부분의 값이 뒷부분보다 작을 경우, 앞부분의 element 추가 | |
if front_idx > 0 and front_value <= end_value: | |
front_idx -= 1 | |
front_value += cookie[front_idx] | |
# 뒷부분의 값이 앞부분보다 작을 경우 뒷부분의 element 추가 | |
elif end_idx < len(cookie)-1 and front_value >= end_value: | |
end_idx += 1 | |
end_value += cookie[end_idx] | |
else: | |
break | |
return max_value |
반응형
'프로그래밍 > 코딩테스트 문제풀이' 카테고리의 다른 글
[Python] 프로그래머스. 단속카메라 (Level 3) (0) | 2019.11.27 |
---|---|
[Python] 백준 3190. 뱀 (0) | 2019.11.26 |
[Python] 백준 14890. 경사로 (0) | 2019.11.24 |
[Python] 프로그래머스. 등굣길 (Level 3) (0) | 2019.11.23 |
[Python] 백준 14499. 주사위 굴리기 (0) | 2019.11.21 |