0%

maximum-subarray

Maximum Subarray – LeetCode 53

Problem

Description

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

Example

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int res = INT_MIN, curSum = 0;
for (int num : nums) {
curSum = max(curSum + num, num);
res = max(res, curSum);
}
return res;
}
};

思路

这里使用动态规划,curSum保存局部最优解,res保存全局最优解。在curSum部分,选择当前值和累加值,意味着若累加值不能给当前值带来贡献则舍弃。这样将在一次遍历中生成所有局部最优解,然后通过res进行记录,最后返回答案。时间复杂度$O(n)$,空间复杂度$O(1)$。

Better

思路

更多的可以在Wiki看到