53. Maximum Subarray
Describe:
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.
Analysis
用的是基本的dp算法,定义一个当前子串的最大值max_temp和一个总的最大值sum。在遍历数组时,max_temp = max( max_temp+nums[i], nums[i])。显然,如果前面的数字加上当前数字之和比当前数字还小,则直接从当前数字开始重新计算子串最大值;否则将当前数字加入前面的子串中。每更新一次max_temp时,都更新sum: sum = max(max_temp, sum)。
另外,在discuss中有分析:
this problem was discussed by Jon Bentley (Sep. 1984 Vol. 27 No. 9 Communications of the ACM P885)
the paragraph below was copied from his paper (with a little modifications)
algorithm that operates on arrays: it starts at the left end (element A[1]) and scans through to the right end (element A[n]), keeping track of the maximum sum subvector seen so far. The maximum is initially A[0]. Suppose we’ve solved the problem for A[1 … i - 1]; how can we extend that to A[1 … i]? The maximum
sum in the first I elements is either the maximum sum in the first i - 1 elements (which we’ll call MaxSoFar), or it is that of a subvector that ends in position i (which we’ll call MaxEndingHere).
MaxEndingHere is either A[i] plus the previous MaxEndingHere, or just A[i], whichever is larger.
public static int maxSubArray(int[] A) {
int maxSoFar=A[0], maxEndingHere=A[0];
for (int i=1;i<A.length;++i){
maxEndingHere= Math.max(maxEndingHere+A[i],A[i]);
maxSoFar=Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
以下是我的代码,发现a+=b比a=a+b要快很多…之前从没注意到,大概是寄存器数量的原因吧qaq
Code
class Solution {
public:
int maxSubArray(vector<int>& nums) {
if(nums.size() == 0){
return -1;
}
int sum = nums[0];
int max_temp = nums[0];
for(int i=1; i<nums.size(); i++){
if(max_temp+nums[i] < nums[i]){
max_temp = nums[i];
}
else{
max_temp += nums[i];
}
sum = max(sum, max_temp);
}
return sum;
}
};