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

Lines changed: 31 additions & 0 deletions
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)