Skip to content

Commit 1c32cb4

Browse files
committed
feat: Solve maximum-subarray problem
1 parent 1ac5131 commit 1c32cb4

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

β€Žmaximum-subarray/hu6r1s.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution:
2+
"""
3+
λΆ€λΆ„ν•© ν™œμš©
4+
dp[0] = nums[0]
5+
dp[1] = dp[0] + nums[1] 와 nums[1] 쀑 큰 값을 λ„£λŠ”λ‹€.
6+
[-2, 1]κΉŒμ§€μ˜ ν•©κ³Ό [1]κΉŒμ§€μ˜ ν•© 쀑 큰 값을 λ„£λŠ”λ‹€κ³  μƒκ°ν•˜λ©΄ λœλ‹€.
7+
dp[1] = [1]
8+
dp[2] = dp[1] + nums[2] 와 nums[2] 쀑 큰 값을 λ„£λŠ”λ‹€.
9+
dp[1]μ—μ„œ [-2, 1]λ₯Ό μ„ νƒν–ˆλ‹€λ©΄ [-2, 1, -3]κΉŒμ§€μ˜ ν•©κ³Ό [1]을 μ„ νƒν–ˆλ‹€λ©΄ [1, -3]κΉŒμ§€μ˜ ν•© 쀑 큰 값을 μ„ νƒν•˜κ²Œ λœλ‹€.
10+
dp[2] = [1, -3]
11+
dp[3] = dp[2] + nums[3] 와 nums[3] 쀑 큰 값을 λ„£λŠ”λ‹€.
12+
dp[3]은 [1, -3]에 [4]λ₯Ό μΆ”κ°€ν•˜μ—¬ [1, -3, 4]κΉŒμ§€μ˜ ν•©κ³Ό nums[3]인 4λ₯Ό λΉ„κ΅ν•˜μ—¬ 큰 κ°’μœΌλ‘œ λ„£λŠ”λ‹€.
13+
κ²°κ΅­ 점화식은 dp[i] = max(dp[i-1] + nums[i], nums[i])κ°€ λœλ‹€.
14+
15+
μ‹œκ°„ λ³΅μž‘λ„ (Time Complexity):
16+
- dp 배열을 μ±„μš°κΈ° μœ„ν•΄ ν•œ 번 순회: O(n)
17+
- dp λ°°μ—΄μ—μ„œ μ΅œλŒ“κ°’μ„ μ°ΎκΈ° μœ„ν•΄ ν•œ 번 순회: O(n)
18+
β†’ 총 μ‹œκ°„ λ³΅μž‘λ„: O(n)
19+
20+
곡간 λ³΅μž‘λ„ (Space Complexity):
21+
- dp 배열이 μž…λ ₯ 크기만큼 ν•„μš”: O(n)
22+
β†’ 총 곡간 λ³΅μž‘λ„: O(n)
23+
"""
24+
def maxSubArray(self, nums: List[int]) -> int:
25+
dp = [0] * len(nums)
26+
dp[0] = nums[0]
27+
28+
for i in range(1, len(nums)):
29+
dp[i] = max(dp[i-1] + nums[i], nums[i])
30+
31+
return max(dp)

0 commit comments

Comments
Β (0)