Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitfbc8eb1

Browse files
committed
53-maximum-subarray.md AddedSolution 1: Greedy Algorithm
1 parenta50eb27 commitfbc8eb1

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
classSolution:
108109
defmaxSubArray(self,nums: List[int]) ->int:
109-
dp= nums.copy()
110+
result=-float('inf')
111+
pre_sum=0
112+
113+
for numin 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+
classSolution:
123+
defmaxSubArray(self,nums: List[int]) ->int:
124+
dp= nums.copy()
125+
111126
for iinrange(1,len(dp)):
112127
dp[i]=max(nums[i], dp[i-1]+ nums[i])
113-
128+
114129
returnmax(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
classSolution:
108109
defmaxSubArray(self,nums: List[int]) ->int:
109-
dp= nums.copy()
110+
result=-float('inf')
111+
pre_sum=0
112+
113+
for numin 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+
classSolution:
123+
defmaxSubArray(self,nums: List[int]) ->int:
124+
dp= nums.copy()
125+
111126
for iinrange(1,len(dp)):
112127
dp[i]=max(nums[i], dp[i-1]+ nums[i])
113-
128+
114129
returnmax(dp)
115130
```
116131

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp