问题描述:
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
题源:here;完整实现:here
思路:
一个one-pass的方案:从头开始记录输入数组的和maxSum
,当maxSum<0
时重新记录,并用另一个变量记录maxSum
的最大值。代码如下:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int maxSum = INT_MIN, result = INT_MIN;
for (int i = 0; i < nums.size(); i++){
if (maxSum < 0) maxSum = nums[i];
else maxSum += nums[i];
result = max(result, maxSum);
}
return result;
}
};