forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathseungriyou.py
More file actions
44 lines (33 loc) · 1.02 KB
/
seungriyou.py
File metadata and controls
44 lines (33 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# https://leetcode.com/problems/maximum-subarray/
from typing import List
class Solution:
def maxSubArray1(self, nums: List[int]) -> int:
"""
[Complexity]
- TC: O(n)
- SC: O(n)
[Approach]
dp[i] = nums[i]까지 봤을 때, (1) nums[i]가 포함되면서 (2) 가장 sum이 큰 subarray의 sum 값
= max(dp[i - 1] + num, num)
"""
n = len(nums)
dp = [0] * n
dp[0] = nums[0]
max_sum = nums[0]
for i in range(1, n):
dp[i] = max(dp[i - 1] + nums[i], nums[i])
max_sum = max(max_sum, dp[i])
return max_sum
def maxSubArray(self, nums: List[int]) -> int:
"""
[Complexity]
- TC: O(n)
- SC: O(1)
[Approach]
space optimized DP
"""
prev = max_sum = nums[0]
for i in range(1, len(nums)):
prev = max(prev + nums[i], nums[i])
max_sum = max(max_sum, prev)
return max_sum