Skip to content

Commit 10e04dd

Browse files
committed
add 53 maximum subarray
1 parent 1a74c9d commit 10e04dd

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
---
2+
layout: leetcode
3+
title: "53. Maximum Subarray"
4+
categories: [leetcode]
5+
---
6+
7+
[Leetcode Link](https://leetcode.com/problems/maximum-subarray/)
8+
9+
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
10+
11+
12+
```
13+
Example 1:
14+
15+
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
16+
Output: 6
17+
Explanation: [4,-1,2,1] has the largest sum = 6.
18+
19+
Example 2:
20+
21+
Input: nums = [1]
22+
Output: 1
23+
24+
Example 3:
25+
26+
Input: nums = [5,4,-1,7,8]
27+
Output: 23
28+
29+
30+
Constraints:
31+
32+
1 <= nums.length <= 3 * 104
33+
-105 <= nums[i] <= 105
34+
```
35+
36+
# Solution
37+
38+
## prefix sum
39+
40+
T: O(n), S:O(n)
41+
42+
```python
43+
def maxSubArray(self, nums: List[int]) -> int:
44+
for i in range(1, len(nums)):
45+
if nums[i-1] > 0:
46+
nums[i] += nums[i-1]
47+
return max(nums)
48+
```
49+
50+
## Kadane's algorithm
51+
52+
T: O(n), S:O(n)
53+
54+
```python
55+
def maxSubArray(self, nums: List[int]) -> int:
56+
# Initialize our variables using the first element.
57+
current_subarray = max_subarray = nums[0]
58+
59+
# Start with the 2nd element since we already used the first one.
60+
for num in nums[1:]:
61+
# If current_subarray is negative, throw it away.
62+
# Otherwise, keep adding to it.
63+
current_subarray = max(num, current_subarray + num)
64+
max_subarray = max(max_subarray, current_subarray)
65+
66+
return max_subarray
67+
```

media/js/tag-search-data.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,13 @@ var problems = {
135135
templates: ["backtrack"],
136136
notes: "Backtrack template. bt(grid, 0). End condition: row==len(grid). diag_l[row+col], diag_r[col-row+n-1], grid[row][col]='Q';bt();grid[row][col]='.'. Time: O(N!), Space: O(N!)",
137137
},
138+
"53": {
139+
name: "53. maximum-subarray",
140+
tags: ["array", "prefix_sum"],
141+
keywords: ["subarray", "sum", "lv_1"],
142+
url: "/leetcode/53-maximum-subarray",
143+
notes: "Kadane's algorithm. Or get prefix sum for array, convert to buy/sell stock problem",
144+
},
138145
"75": {
139146
name: "75. Sort Colors",
140147
tags: ["array", "two_pointers"],

0 commit comments

Comments
 (0)