Skip to content
This repository was archived by the owner on Mar 18, 2024. It is now read-only.

[2023-09-11] dohyun #204 #217

Merged
merged 1 commit into from
Sep 12, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions BOJ/연속합/dohyun.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""

풀이시간
- 1시간 풀이 후 실패로 답지 참고

접근법
- N 이 십만 이하 -> 최대 O(NlogN) 으로 접근
- 연속된 몇개의 수 -> 순서는 보존된 상태로 풀어내야함
- 부분합은 중복되는 계산이 굉장히 많음 -> DP로 해결해보자

- 틀린 풀이
- 고르는 숫자의 개수(n) 에 대한 dp 테이블을 만들고 값으로는 최대값을 넣어보자
- 여러 예제를 만들어본 결과 배열 내 최대값은 고정으로 들어가는 것 같음
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 가정이 틀린 풀이가 나온 가장 큰 이유가 아닐까 싶습니다.
[99, -1, -99, 98]
이 예제에서는 제일 큰 수 99가 배열에 수열에 포함되면 안되니까요!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@zsmalla 으으음 제일 큰 수 99 딱 하나를 고르면 되기 때문에 결국 제일 큰 수가 배열에 포함되는 것이 아닐까요?!
제 기존 풀이로는 max(dp) 의 결과로 dp[1] = max(arr) 이 뽑히긴 합니다..!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@zsmalla 으으음 제일 큰 수 99 딱 하나를 고르면 되기 때문에 결국 제일 큰 수가 배열에 포함되는 것이 아닐까요?! 제 기존 풀이로는 max(dp) 의 결과로 dp[1] = max(arr) 이 뽑히긴 합니다..!

헐 맞네요 그 생각을 못했습니다 ㅎㅎ.. 그럼 저 경우는 해당 안될 것 같고, [99 -1 60 61] 이런 경우??

- dp[1] 에 가장 큰 수를 넣으면 가장 큰 수를 고정으로 넣은 것과 같음
- 따라서 고르는 숫자의 개수가 1개 늘어나면 왼쪽에 하나 추가한거랑 오른쪽에 하나 추가한거 비교해서 더 큰것으로 선택
- 의사 코드 (점화식?)
Copy link
Contributor

@ksumini ksumini Sep 11, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

반례 찾아드리려고 했는데 아래 써준 점화식이랑 설명 이해를 못했어요 ㅠㅠ 다음 번에는 아예 코드로 적어주셔도 좋을 것 같아요 도현님!

```
left_sum = dp[i-1] + arr[left_idx - 1]
right_sum = dp[i-1] + arr[right_idx + 1]
dp[i] = max(left_sum, right_sum)
left_idx 또는 right_idx 업데이트
```
- 주어진 예제 외에도 테스트케이스를 10개 정도 만들어서 돌려봤는데도 잘 나오는데, 제출하면 틀림 ...

- 정답 풀이
- 그냥 왼쪽부터 순회하며 이전값 + 현재값이 더 크면 연속합 갱신해주고, 현재값이 더 크면 이전 합들을 다 버리고 새로 시작하면 됨

회고
- DP 문제는 테이블 설정 또는 점화식 접근을 잘 못하는 순간 완전 잘못된 방향으로 가는 것 같다
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

너무 공감됩니다... 이번 문제는 저도 운좋게 풀이 할 수 있었지만 다른 문제들은 그게 너무 어려운 것 같아요 ㅠㅠ

- 다른 유형들에 비해 특히나 더 사전에 생각을 많이하고 풀이 시작하기

"""

import sys

inputs = sys.stdin.readline
n = int(inputs())
arr = list(map(int, inputs().rstrip().split()))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

split()을 사용하실 때는 whitespace가 모두 사라져서 rstrip은 안 써주어도 될 것 같습니다!


for i in range(1, n):
arr[i] = max(arr[i], arr[i-1] + arr[i])

print(max(arr))