Skip to content

Commit fbc8eb1

Browse files
committed
53-maximum-subarray.md Added Solution 1: Greedy Algorithm
1 parent a50eb27 commit fbc8eb1

File tree

2 files changed

+35
-5
lines changed

2 files changed

+35
-5
lines changed

en/1-1000/53-maximum-subarray.md

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ Constraints:
3535
```
3636

3737
## Thoughts
38-
* This problem can be solved by using `greedy algorithm`, but here we will use another way.
38+
* This problem can be solved by using `greedy algorithm` (please see `solution 1` in Python), but here we will use another way.
3939
* Imagine the size of nums is `i`, let us consider if the same question is applied to the `subarray` of `nums` from index `0` to `i - 1`.
4040
* The answer is `yes`. Then let us think if the `i - 1`'s answer could impact the answer of `i`.
4141
* The answer is still `yes`. What would be the impact?
@@ -103,14 +103,29 @@ public class Solution
103103
```
104104

105105
## Python
106+
### Solution 1: Greedy Algorithm
106107
```python
107108
class Solution:
108109
def maxSubArray(self, nums: List[int]) -> int:
109-
dp = nums.copy()
110+
result = -float('inf')
111+
pre_sum = 0
112+
113+
for num in nums:
114+
pre_sum = max(pre_sum + num, num)
115+
result = max(result, pre_sum)
110116

117+
return result
118+
```
119+
120+
### Solution 2: Dynamic Programming
121+
```python
122+
class Solution:
123+
def maxSubArray(self, nums: List[int]) -> int:
124+
dp = nums.copy()
125+
111126
for i in range(1, len(dp)):
112127
dp[i] = max(nums[i], dp[i - 1] + nums[i])
113-
128+
114129
return max(dp)
115130
```
116131

zh/1-1000/53-maximum-subarray.md

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,14 +103,29 @@ public class Solution
103103
```
104104

105105
## Python
106+
### Solution 1: Greedy Algorithm
106107
```python
107108
class Solution:
108109
def maxSubArray(self, nums: List[int]) -> int:
109-
dp = nums.copy()
110+
result = -float('inf')
111+
pre_sum = 0
112+
113+
for num in nums:
114+
pre_sum = max(pre_sum + num, num)
115+
result = max(result, pre_sum)
110116

117+
return result
118+
```
119+
120+
### Solution 2: Dynamic Programming
121+
```python
122+
class Solution:
123+
def maxSubArray(self, nums: List[int]) -> int:
124+
dp = nums.copy()
125+
111126
for i in range(1, len(dp)):
112127
dp[i] = max(nums[i], dp[i - 1] + nums[i])
113-
128+
114129
return max(dp)
115130
```
116131

0 commit comments

Comments
 (0)