Skip to content

Commit 998a10b

Browse files
committed
Add solution for Maximun subarray
1 parent 8b6e421 commit 998a10b

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

โ€Žmaximum-subarray/KwonNayeon.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""
2+
Conditions:
3+
- 1 <= nums.length <= 10^5
4+
- -10^4 <= nums[i] <= 10^4
5+
6+
Time Complexity: O(n)
7+
- ๋ฐฐ์—ด์„ ํ•œ ๋ฒˆ๋งŒ ์ˆœํšŒํ•จ
8+
9+
Space Complexity: O(1)
10+
- ๋‘ ๋ณ€์ˆ˜ ์ด์™ธ์— ์ถ”๊ฐ€ ๊ณต๊ฐ„์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์Œ
11+
12+
ํ’€์ด๋ฐฉ๋ฒ•:
13+
1. Base case: If nums is empty, return 0
14+
2. Initialize variables (current_sum and max_sum as the first value in the array)
15+
3. Traverse from the value at 1st index to the last, update current_sum
16+
- Decide whether to add the current value (num) to the existing subarray or start a new one
17+
4. Update max_sum
18+
- Choose the larger between the updated current_sum and the previous max_sum
19+
"""
20+
class Solution:
21+
def maxSubArray(self, nums: List[int]) -> int:
22+
if not nums:
23+
return 0
24+
25+
current_sum = max_sum = nums[0]
26+
27+
for num in nums[1:]:
28+
current_sum = max(num, current_sum + num)
29+
max_sum = max(current_sum, max_sum)
30+
31+
return max_sum

0 commit comments

Comments
ย (0)