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
.
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
这道题是找相加和最大的连续子数组,题目难度为Medium。
这道题典型的解决办法是Kadane's algorithm,不知道算法名无所谓,相信大家也能想到实现细节。逐个遍历数组元素并将其加入累加和(sum),如果累加和大于记录的最大和(maxSum),更新maxSum,如果sum小于等于0,表明之前的子数组不会提高后续数组的相加和,抛弃之前的子数组,将sum重新置为0,这样遍历数组即可得到maxSum。具体代码:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int sum = 0, maxSum = INT_MIN;
for(int num:nums) {
sum += num;
maxSum = max(maxSum, sum);
if(sum < 0) sum = 0;
}
return maxSum;
}
};
如果要得到最大和子数组的起始和结束为止,可以用下面的方法:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int sum = 0, maxSum = INT_MIN;
int l = 0, r = 0, maxL = 0, maxR = 0;
for(int i=0; i<nums.size(); ++i) {
sum += nums[i];
if(sum > maxSum) {
maxSum = sum;
r = i;
maxL = l;
maxR = r;
}
if(sum < 0) {
sum = 0;
l = i + 1;
r = l;
}
}
return maxSum;
};
上面介绍的Kadane's algorithm不仅可以求连续子数组的最大和,还可以求最小和,方法是一样的。
另外,题目要求用分治法解题,就再来个分治法的版本。对任意位置元素,如果该元素在最大和子数组内部,可以以该元素为中心向两边逐个加数组元素,判断包含该元素在内部的子数组的最大和;如果该元素不在最大和子数组内部,可以在此元素位置将数组划分为两个独立数组,分别求这两个数组的连续子数组最大和,这样就把问题通过分治法分割为了两个相同的子问题,通过比较这三个最大和即可得到最终结果。具体代码:
class Solution {
int getMaxSum(const vector<int>& nums, int bgn, int end) {
if(bgn == end) return nums[bgn];
int mid = (bgn + end) / 2;
int lMaxSum = INT_MIN, rMaxSum = INT_MIN, sum = 0;
for(int i=mid; i>=bgn; --i) {
sum += nums[i];
lMaxSum = max(lMaxSum, sum);
}
sum = 0;
for(int i=mid+1; i<=end; ++i) {
sum += nums[i];
rMaxSum = max(rMaxSum, sum);
}
int left = getMaxSum(nums, bgn, mid);
int right = getMaxSum(nums, mid+1, end);
return max(max(left, right), lMaxSum+rMaxSum);
}
public:
int maxSubArray(vector<int>& nums) {
if(nums.empty()) return 0;
return getMaxSum(nums, 0, nums.size()-1);
}
};