forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththispath98.py
More file actions
37 lines (33 loc) Β· 1.32 KB
/
thispath98.py
File metadata and controls
37 lines (33 loc) Β· 1.32 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
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
"""
Intuition:
μ΄μ κΉμ§μ λμ ν©μμ νμ¬ μμλ₯Ό μΆκ°ν μ§ λ§μ§μ λν
κ²°μ μ λ§€ iterationλ§λ€ λ°λ³΅νλ€.
νμ¬ μμλ₯Ό μΆκ°νμ κ²½μ°(λμ ν© + νμ¬ μμ)μ
νμ¬ μμλ₯Ό μμμΌλ‘ νλ κ²½μ°(νμ¬ μμ)λ₯Ό λΉκ΅νμ¬
dp λ°°μ΄μ κ°±μ νλ€.
Time Complexity:
O(N):
리μ€νΈλ₯Ό 1λ² μννλ©° λ΅μ μ°ΎμΌλ―λ‘,
O(N)μ μκ°λ³΅μ‘λκ° μμλλ€.
Space Complexity:
O(N):
dp λ°°μ΄μ Nκ°μ time stepμ μ μ₯νλ―λ‘
O(N)μ 곡κ°λ³΅μ‘λκ° μμλλ€.
Key takeaway:
μ΄κΈ°μλ two pointer λ°©μμ μκ°νμΌλ
ν΄κ²°μ νμ§ λͺ»ν΄μ λ΅μμ νμΈνλ€.
O(N)μ μκ°λ³΅μ‘λλ₯Ό κ°μ§λ κ²½μ°, DPλ νμ΄κ°
λ μ μμμ μΈμ§νμ.
"""
dp = [0 for _ in nums]
dp[0] = nums[0]
for i in range(1, len(nums)):
cumsum = dp[i - 1] + nums[i]
cur = nums[i]
if cumsum > cur:
dp[i] = cumsum
else:
dp[i] = cur
return max(dp)