1 public int maxSubArray(int[] A) { 2 int newsum=A[0]; 3 int max=A[0]; 4 for(int i=1;i<A.length;i++){ 5 newsum=Math.max(newsum+A[i],A[i]); 6 max= Math.max(max, newsum); 7 } 8 return max; 9 }
1 int maxSubArray(int *a, const int length) 2 { 3 int maxSumSubArray = 0; 4 int sum_i = 0; 5 for(int i=0; i <length; i++) 6 { 7 sum_i = sum_i + a[i]; 8 if(sum_i < 0) sum_i = 0; 9 else 10 { 11 if(sum_i > maxSumSubArray) maxSumSubArray = sum_i; 12 } 13 } 14 15 //若是数组中的元素均为负值 16 if(sum_i==0) 17 { 18 for(int i=0; i < length; i++) 19 { 20 if(a[i] > maxSumSubArray) maxSumSubArray = a[i]; 21 } 22 } 23 return maxSumSubArray; 24 }
还有一种是分治算法 自己写的 复杂度O(nlogn)
1 #include<iostream> 2 using namespace std; 3 int MaxSubArray(int *A,int low,int high){ 4 if(low==high) return A[low]; 5 int mid=(low+high)/2; 6 int maxl=MaxSubArray(A,low,mid); 7 int maxr=MaxSubArray(A,mid+1,high); 8 int maxleft=A[mid],maxright=A[mid+1],maxsum; 9 maxsum=A[mid]; 10 if(mid-1>=low) 11 for(int i=mid-1;i>=low;i--){ 12 maxsum=maxsum+A[i]; 13 maxleft=max(maxsum,maxleft); 14 } 15 maxsum=A[mid+1]; 16 if(mid+2<=high) 17 for(int i=mid+2;i<=high;i++){ 18 maxsum=maxsum+A[i]; 19 maxright=max(maxsum,maxright); 20 } 21 int cross=maxleft+maxright; 22 return max(cross,max(maxl,maxr)); 23 24 } 25 int main(){ 26 int a[]={1,-4,1,3,-4,2}; 27 cout<<MaxSubArray(a,0,5)<<endl; 28 return 0; 29 }