Skip to content

Commit d141ec5

Browse files
committed
🎉 #53. Maximum Subarray
1 parent 94361ac commit d141ec5

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/*
2+
* @Author: Goog Tech
3+
* @Date: 2020-09-15 13:44:15
4+
* @LastEditTime: 2020-09-15 13:44:36
5+
* @Description: https://leetcode-cn.com/problems/maximum-subarray/
6+
* @FilePath: \leetcode-googtech\#53. Maximum Subarray\Solution.java
7+
* @WebSite: https://algorithm.show/
8+
*/
9+
10+
class Solution {
11+
// DP : 动态规划,解题思路如下所示:
12+
// 1. 首先对数组进行遍历,设当前最大连续子序列和为 sum, 结果为 result
13+
// 2. 若 sum > 0,则说明 sum 对结果有增益效果,进而将当前所遍历的数字累加到 sum
14+
// 3. 若 sum <= 0,则说明 sum 对结果无增益效果,进而舍弃当前所遍历数字,并将 sum 更新为当前所遍历的数字
15+
// 4. 每次比较 sum 与 result 的大小,即将最大值置为 result,遍历结束后返回结果即可
16+
public int maxSubArray(int[] nums) {
17+
int result = nums[0], sum = 0;
18+
for(int num : nums) {
19+
if(sum > 0) sum += num;
20+
else sum = num;
21+
result = Math.max(result, sum);
22+
}
23+
return result;
24+
}
25+
}

#53. Maximum Subarray/Solution.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
'''
2+
Author: Goog Tech
3+
Date: 2020-09-15 13:44:20
4+
LastEditTime: 2020-09-15 13:44:46
5+
Description: https://leetcode-cn.com/problems/maximum-subarray/
6+
FilePath: \leetcode-googtech\#53. Maximum Subarray\Solution.py
7+
WebSite: https://algorithm.show/
8+
'''
9+
10+
class Solution(object):
11+
# DP : 动态规划
12+
def maxSubArray(self, nums):
13+
"""
14+
:type nums: List[int]
15+
:rtype: int
16+
"""
17+
for i in range(1, len(nums)):
18+
if nums[i - 1] > 0:
19+
nums[i] += nums[i - 1]
20+
return max(nums)

0 commit comments

Comments
 (0)