forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhi-rachel.py
More file actions
35 lines (31 loc) · 982 Bytes
/
hi-rachel.py
File metadata and controls
35 lines (31 loc) · 982 Bytes
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
# 최대 부분 배열 합 문제
# O(n^2) time, O(1) space
# Time Limit Exceeded
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
max_total = nums[0]
for i in range(len(nums)):
total = 0
for j in range(i, len(nums)):
total += nums[j]
max_total = max(total, max_total)
return max_total
# 개선 풀이
# O(n) time, O(1) space
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
max_total = nums[0]
total = nums[0]
for i in range(1, len(nums)):
total = max(nums[i], total + nums[i])
max_total = max(total, max_total)
return max_total
# DP 풀이
# O(n) time, O(n) space
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
dp = [0] * len(nums)
dp[0] = nums[0]
for i in range(1, len(nums)):
dp[i] = max(nums[i], dp[i - 1] + nums[i])
return max(dp)