Skip to content

Commit b70e1f1

Browse files
authored
Create 53_Maximum_Subarray.md
1 parent 94d8699 commit b70e1f1

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

53_Maximum_Subarray.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
## 53. Maximum Subarray
2+
3+
```
4+
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
5+
6+
7+
8+
Example 1:
9+
10+
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
11+
Output: 6
12+
Explanation: [4,-1,2,1] has the largest sum = 6.
13+
Example 2:
14+
15+
Input: nums = [1]
16+
Output: 1
17+
Example 3:
18+
19+
Input: nums = [5,4,-1,7,8]
20+
Output: 23
21+
22+
23+
Constraints:
24+
25+
1 <= nums.length <= 3 * 104
26+
-105 <= nums[i] <= 105
27+
28+
29+
Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
30+
```
31+
32+
```python
33+
def maxSubArray(self, nums: List[int]) -> int:
34+
# Kadane's Algorithm
35+
max_cur = nums[0]
36+
max_global = nums[0]
37+
38+
for i in range(1, len(nums)):
39+
max_cur = max(nums[i], max_cur + nums[i])
40+
if max_cur > max_global:
41+
max_global = max_cur
42+
43+
return max_global
44+
```
45+
46+
```
47+
Runtime: 80 ms, faster than 15.49% of Python3 online submissions for Maximum Subarray.
48+
Memory Usage: 14.9 MB, less than 60.64% of Python3 online submissions for Maximum Subarray.
49+
```

0 commit comments

Comments
 (0)