来源:Leetcode Problem Set - Algorithm Problem53
题目描述:
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
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
.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
解题思路:动态规划问题,在一边扫描中维护两个值,一个是到目前扫描位置所有元素中的最大和,一个是目前为止包括当前扫描元素的最大和,扫描完毕后得到最优解
题解代码:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
if (nums.size() == 0) return 0;
int global = nums[0];
int local = nums[0];
for (int i = 1; i < nums.size(); i++) {
if (nums[i] > local + nums[i])
local = nums[i];
else
local = local + nums[i];
if (local > global)
global = local;
}
return global;
}
};