题目内容
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.
此题来自LeetCode。
解题思路
首先此题是使用分治的思想来解题
把数组分成左右两部分,分别求两部分的最大子数组。当然,不能排除存在跨越两者的最大子数组。最后把这三部分进行比较。其中最重要的是求中间的部分。本例中,采取不断从中间往左边扫描,取其最大的部分,再往右扫描
代码示例
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int high=nums.size()-1;
return maxSub(nums,0,high);
}
int maxSub(vector<int>& array,int low,int high) {
if(low==high) {
return array[low]; //最底层递归返回的条件
}
int mid=(low+high)/2;
int leftMax=maxSub(array,low,mid);//左边的最大值
int rightMax=maxSub(array,mid+1,high);//右边的最大值
int middleMax=array[mid];
//先从中间往左边算,找出从中间到左边的最大值
for(int i=mid-1,temp=middleMax;i>=low;--i) {
temp+=array[i];
middleMax=max(middleMax,temp);
}
//然后连接右边,找出跨越左右的最大值
for(int i=mid+1,temp=middleMax;i<=high;++i) {
temp+=array[i];
middleMax=max(middleMax,temp);
}
return max(middleMax,max(leftMax,rightMax)); //找出左边,右边,还是跨越两边的最大值;
}
int max(int a,int b) {
if(a>b) return a;
return b;
}
};