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
.
这道题目就不废话了,在《编程珠玑》的“算法设计技术”那一章中的重点介绍的。这题不会做就是你的问题了!!!
这是平方的算法,在大数据平方算法耗时1616ms
class Solution {
public:
int maxSubArray(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int sum=0;
int max=0x80000000;
for(int i=0 ; i<n ; i++){
sum=0;
for(int j=i ; j<n ; j++){
sum+=A[j];
if(sum>max)
max=sum;
}
}
return max;
}
};
然后是o(nlogn)的算法,大数据下面耗时为56ms,可以看出来好多了!!!!:
class Solution {
public:
#define MIX 0x80000000
int maxSubArray(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return _maxSubArray(A,0,n-1);
}
int _maxSubArray(int A[], int left, int right){
int maxleft,maxright,sumleft,sumright;
maxleft=MIX,maxright=MIX,sumleft=0,sumright=0;
if(left>right)
return MIX;
if(left==right)
return A[left];
int middle=((right-left)>>1)+left;
for(int i=middle;i>=left;i--){
sumleft+=A[i];
if(sumleft>maxleft)
maxleft=sumleft;
}
for(int j=middle+1;j<=right;j++){
sumright+=A[j];
if(sumright>maxright)
maxright=sumright;
}
return max(max(maxleft+maxright,_maxSubArray(A,left,middle)),_maxSubArray(A,middle+1,right));
}
};
最后是线性算法,其实有一定的局限性,就是加减法不能溢出,大数据耗时:40ms
class Solution {
public:
#define MIX 0xFFF00000
int maxSubArray(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int maxpending,maxsofar;
maxpending=0xFFF00000,maxsofar=0xFFF00000;
for(int i=0 ;i<n ; i++){
maxpending=max(maxpending+A[i],A[i]);
maxsofar=max(maxsofar,maxpending);
}
return maxsofar;
}
};
上面说明了o(n*logn)的算法跟线性算法的时间复杂度还是比较接近的。