forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKwonNayeon.py
More file actions
31 lines (25 loc) Β· 924 Bytes
/
KwonNayeon.py
File metadata and controls
31 lines (25 loc) Β· 924 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
"""
Conditions:
- 1 <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
Time Complexity: O(n)
- λ°°μ΄μ ν λ²λ§ μνν¨
Space Complexity: O(1)
- λ λ³μ μ΄μΈμ μΆκ° 곡κ°μ μ¬μ©νμ§ μμ
νμ΄λ°©λ²:
1. Base case: If nums is empty, return 0
2. Initialize variables (current_sum and max_sum as the first value in the array)
3. Traverse from the value at 1st index to the last, update current_sum
- Decide whether to add the current value (num) to the existing subarray or start a new one
4. Update max_sum
- Choose the larger between the updated current_sum and the previous max_sum
"""
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
if not nums:
return 0
current_sum = max_sum = nums[0]
for num in nums[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(current_sum, max_sum)
return max_sum