Skip to content

Commit 6f1fe57

Browse files
committed
📝 docs : add 53. 最大子序和.md
1 parent d141ec5 commit 6f1fe57

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
## 53. 最大子序和
2+
> https://leetcode-cn.com/problems/maximum-subarray/
3+
4+
5+
### Java
6+
```java
7+
/*
8+
* @Author: Goog Tech
9+
* @Date: 2020-09-15 13:44:15
10+
* @LastEditTime: 2020-09-15 13:44:36
11+
* @Description: https://leetcode-cn.com/problems/maximum-subarray/
12+
* @FilePath: \leetcode-googtech\#53. Maximum Subarray\Solution.java
13+
* @WebSite: https://algorithm.show/
14+
*/
15+
16+
class Solution {
17+
// DP : 动态规划,解题思路如下所示:
18+
// 1. 首先对数组进行遍历,设当前最大连续子序列和为 sum, 结果为 result
19+
// 2. 若 sum > 0,则说明 sum 对结果有增益效果,进而将当前所遍历的数字累加到 sum
20+
// 3. 若 sum <= 0,则说明 sum 对结果无增益效果,进而舍弃当前所遍历数字,并将 sum 更新为当前所遍历的数字
21+
// 4. 每次比较 sum 与 result 的大小,即将最大值置为 result,遍历结束后返回结果即可
22+
public int maxSubArray(int[] nums) {
23+
int result = nums[0], sum = 0;
24+
for(int num : nums) {
25+
if(sum > 0) sum += num;
26+
else sum = num;
27+
result = Math.max(result, sum);
28+
}
29+
return result;
30+
}
31+
}
32+
```
33+
34+
### Python
35+
```python
36+
'''
37+
Author: Goog Tech
38+
Date: 2020-09-15 13:44:20
39+
LastEditTime: 2020-09-15 13:44:46
40+
Description: https://leetcode-cn.com/problems/maximum-subarray/
41+
FilePath: \leetcode-googtech\#53. Maximum Subarray\Solution.py
42+
WebSite: https://algorithm.show/
43+
'''
44+
45+
class Solution(object):
46+
# DP : 动态规划
47+
def maxSubArray(self, nums):
48+
"""
49+
:type nums: List[int]
50+
:rtype: int
51+
"""
52+
for i in range(1, len(nums)):
53+
if nums[i - 1] > 0:
54+
nums[i] += nums[i - 1]
55+
return max(nums)
56+
```

docs/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
* [28.实现strStr()](LeetCode刷题之旅及题目解析/28.实现strStr/28.实现strStr.md)
3434
* [35.搜索插入位置](LeetCode刷题之旅及题目解析/35.搜索插入位置/35.搜索插入位置.md)
3535
* [41.缺失的第一个正数](LeetCode刷题之旅及题目解析/41.缺失的第一个正数/41.缺失的第一个正数.md)
36+
* [53.最大子序和](LeetCode刷题之旅及题目解析/53.最大子序和/53.最大子序和.md)
3637
* [58.最后一个单词的长度](LeetCode刷题之旅及题目解析/58.最后一个单词的长度/58.最后一个单词的长度.md)
3738
* [66.加一](LeetCode刷题之旅及题目解析/66.加一/66.加一.md)
3839
* [82.删除排序链表中的重复元素II](LeetCode刷题之旅及题目解析/82.删除排序链表中的重复元素II/82.删除排序链表中的重复元素II.md)

0 commit comments

Comments
 (0)