Description:
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.
Solution:
1.暴力解法:
利用枚举思想,列举所有情况。显然时间复杂度达到O(n²)。
2.分治法:
三个步骤,划分->递归求解->合并问题,这个问题显然是可以这样做的。时间复杂度变为O(nlogn)。
//伪代码
int maxsum(int *A, int x, int y) {
int i, m, v, L, R, max;
if (y-x == 1) return A[x];
m = x + (y-x)/2;
max = maxsum(A, x, m) >? masum(A, m, y);
v = 0;
L = A[m-1];
for (i = m-1; i>= x; i--) L >?= v += A[i];
v = 0;
R = A[m];
for (i = m; i < y; i++) R >?= v += A[i];
return max >? (L+R);
}
3.O(n)算法
这个算法显然是巧妙的,考虑一个连续数组,对于求其连续最大和,遍历整个数组。显然,对于任何一个大于0的连续和S[i],它们加上大于0的nums[i+1]都能够得到一个当前最大的连续和。其时间复杂度为O(n)。
//6 ms
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int maxSum = 0;
int curSum = 0;
int mayMaxSum = nums[0];
for (int i = 0; i < nums.size(); i++) {
curSum += nums[i];
if (curSum > maxSum) maxSum = curSum;
if (curSum <= 0) {
if (mayMaxSum < curSum) mayMaxSum = curSum;
curSum = 0;
}
}
if (maxSum == 0) return mayMaxSum;
return maxSum;
}
};