Skip to content

Commit b00c57f

Browse files
committed
add solution: maximum-subarray
1 parent 0dff36a commit b00c57f

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

β€Žmaximum-subarray/ZetBe.pyβ€Ž

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
'''
2+
문제: μ΅œλŒ€ λΆ€λΆ„ λ°°μ—΄μ˜ 합을 κ΅¬ν•˜λŠ” 문제
3+
풀이:
4+
1. λ°°μ—΄μ˜ λͺ¨λ“  μˆ˜κ°€ 음수인 경우, κ°€μž₯ 큰 수λ₯Ό λ°˜ν™˜
5+
2. λ°°μ—΄μ˜ μ²˜μŒλΆ€ν„° μ–‘μˆ˜κ°€ λ‚˜μ˜¬ λ•ŒκΉŒμ§€ 인덱슀λ₯Ό 이동
6+
3. μ–‘μˆ˜κ°€ λ‚˜μ˜¨ μ΄ν›„λΆ€ν„°λŠ” ν˜„μž¬ 합이 μ–‘μˆ˜μΈ λ™μ•ˆμ€ 계속 λ”ν•˜κ³ , μŒμˆ˜κ°€ 되면 λ‹€μ‹œ μ–‘μˆ˜λ₯Ό 찾음
7+
4. λ§€ λ‹¨κ³„λ§ˆλ‹€ μ΅œλŒ€ 합을 κ°±μ‹ 
8+
μ‹œκ°„λ³΅μž‘λ„: O(n)
9+
배열을 ν•œ 번 μˆœνšŒν•˜λ©° μ΅œλŒ€ λΆ€λΆ„ λ°°μ—΄μ˜ 합을 κ³„μ‚°ν•˜λ―€λ‘œ 전체 μ‹œκ°„λ³΅μž‘λ„λŠ” O(n)이닀.
10+
κ³΅κ°„λ³΅μž‘λ„: O(1)
11+
좔가적인 곡간을 μ‚¬μš©ν•˜μ§€ μ•ŠμœΌλ―€λ‘œ 전체 κ³΅κ°„λ³΅μž‘λ„λŠ” O(1)이닀.
12+
'''
13+
14+
15+
class Solution:
16+
def maxSubArray(self, nums: List[int]) -> int:
17+
n = len(nums)
18+
answ = 0
19+
if max(nums) <= 0:
20+
return max(nums)
21+
i = 0
22+
while nums[i] < 0:
23+
i += 1
24+
now = 0
25+
while i < n:
26+
if now > 0 and i < n:
27+
now += nums[i]
28+
i += 1
29+
else:
30+
while now <= 0 and i < n:
31+
now = nums[i]
32+
i += 1
33+
answ = max(answ, now)
34+
35+
return answ
36+

0 commit comments

Comments
Β (0)