Skip to content

Commit ef67ff9

Browse files
committed
feat: add maximum-subarray solution
1 parent e89b1a7 commit ef67ff9

File tree

1 file changed

+37
-4
lines changed

1 file changed

+37
-4
lines changed
Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,46 @@
11
"""
22
[๋ฌธ์ œํ’€์ด]
33
# Inputs
4-
4+
- ์ •์ˆ˜ํ˜• nums
55
# Outputs
6-
6+
- ๋ถ€๋ถ„ ๋ฐฐ์—ด ์ค‘ ํ•ฉ์ด ๊ฐ€์žฅ ํฐ ๋ฐฐ์—ด์˜ ํ•ฉ
77
# Constraints
8-
8+
- 1 <= nums.length <= 10^5
9+
- 10^4 <= nums[i] <= 10^4
910
# Ideas
11+
๊ฐ€์žฅ ํฐ ํ•ฉ์„ ๊ตฌํ•˜๋Š” ๋ฐฉ๋ฒ•
12+
์ •๋ ฌ์€ ๋‹น์—ฐํžˆ X
13+
10^5๊ฐ€ ์ตœ๋Œ€๋ผ O(n) ๊ณ ๋ ค ํ•„์š”
14+
-2 1 -3 4 -1 2 1 -5 4
15+
l, r = 0, 0 -> ์›€์ง์ด๋ฉด์„œ
16+
r = 1
17+
-2 < 1 -> -1
18+
19+
-2 -1 -4 0 -1 1 2 -3 1
20+
1. ๋ˆ„์ ํ•ฉ?
21+
22+
-2 1 -2 4 3 5 6 1 5
23+
24+
5 4 -1 7 8
25+
5 9 8 15 23
26+
27+
์ง€๊ธˆ๊นŒ์ง€์˜ ํ•ฉ ๋ณด๋‹ค ๋‹ค์Œ ์›์†Œ๊ฐ€ ํฌ๋ฉด ๊ทธ๋Œ€๋กœ ๋‘๊ณ , ์•„๋‹ˆ๋ฉด ํ•ฉ์œผ๋กœ ๋Œ€์ฒด
28+
=> TC: O(n), SC: O(1)
1029
1130
[ํšŒ๊ณ ]
31+
๋จผ๊ฐ€..๋•Œ๋ ค ๋งž์ถ˜ ๋А๋‚Œ์ด๋ผ ํ•ด์„ค ์ฐธ๊ณ 
32+
->
33+
"""
34+
35+
class Solution:
36+
def maxSubArray(self, nums: List[int]) -> int:
37+
if len(nums) == 1:
38+
return nums[0]
39+
40+
memo = nums[0]
41+
42+
for i in range(1, len(nums)):
43+
if nums[i] < nums[i - 1] + nums[i]:
44+
nums[i] += nums[i - 1]
1245

13-
"""
46+
return max(nums)

0 commit comments

Comments
ย (0)