Skip to content

Commit 9059ba7

Browse files
committed
solve(w03): 53. Maximum Subarray
1 parent 18c54a3 commit 9059ba7

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

maximum-subarray/seungriyou.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# https://leetcode.com/problems/maximum-subarray/
2+
3+
from typing import List
4+
5+
class Solution:
6+
def maxSubArray1(self, nums: List[int]) -> int:
7+
"""
8+
[Complexity]
9+
- TC: O(n)
10+
- SC: O(n)
11+
12+
[Approach]
13+
dp[i] = nums[i]까지 봤을 때, (1) nums[i]가 포함되면서 (2) 가장 sum이 큰 subarray의 sum 값
14+
= max(dp[i - 1] + num, num)
15+
"""
16+
17+
n = len(nums)
18+
dp = [0] * n
19+
dp[0] = nums[0]
20+
max_sum = nums[0]
21+
22+
for i in range(1, n):
23+
dp[i] = max(dp[i - 1] + nums[i], nums[i])
24+
max_sum = max(max_sum, dp[i])
25+
26+
return max_sum
27+
28+
def maxSubArray(self, nums: List[int]) -> int:
29+
"""
30+
[Complexity]
31+
- TC: O(n)
32+
- SC: O(1)
33+
34+
[Approach]
35+
space optimized DP
36+
"""
37+
38+
prev = max_sum = nums[0]
39+
40+
for i in range(1, len(nums)):
41+
prev = max(prev + nums[i], nums[i])
42+
max_sum = max(max_sum, prev)
43+
44+
return max_sum

0 commit comments

Comments
 (0)