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
.
这是一道很常见的题目了,其实唯一需要注意的是当所有数据均为负数的时候,需要分开讨论,即遍历查找最小值即可。就不多描述了
#include<iostream>
using namespace std;
class Solution{
public:
int maxSubArray( int A[],int n ) {
int temp = 0,max = 0;
int flag = 1;
for( int i = 0;i < n;i++ )
if( A[i] > 0 )
flag = 0;
if( flag ) {
max = A[0];
for( int i = 1;i < n;i++ )
if( max < A[i] )
max = A[i];
return max;
}
for( int i = 0;i < n;i++ ) {
if( A[i] > 0 ) {
temp += A[i];
max = max > temp ? max : temp;
}
else if( temp + A[i] > 0 )
temp += A[i];
else
temp = 0;
}
return max;
}
};
int main()
{
int a[] = { -2,1,-3,4,-1,2,1,-5,4 };
Solution test;
cout << test.maxSubArray( a,9 ) << endl;
return 0;
}