给出一个数组,要求出最大非空连续子数组,使得字数组的和最大。
参照《算法导论》,下面给出递归和非递归版本的C++实现。
template<typename T>
vector<T> FindMaxCrossSubArray(const vector<T>& A, int low, int mid, int high){
T left_sum = -99999999;
T sum=0;
int max_left=mid;
for(int i=mid; i>=low; --i){
sum+=A[i];
if(sum>left_sum){
left_sum=sum;
max_left=i;
}
}
T right_sum = -99999999;
sum=0;
int max_right=mid+1;
for(int i=mid+1; i<=high; ++i){
sum+=A[i];
if(sum>right_sum){
right_sum=sum;
max_right=i;
}
}
vector<T> rst = {max_left, max_right, left_sum+right_sum};
return rst;
}
template<typename T>
vector<T> FindMaxSubArray_reg(const vector<T>& A, int low, int high){
if(low==high){
vector<T> rst={low, high, A[low]};
return rst;
}
else{
int mid = (low+high)/2;
vector<T> rst_left = FindMaxSubArray_reg(A, low, mid);
vector<T> rst_right = FindMaxSubArray_reg(A, mid+1, high);
vector<T> rst_cross = FindMaxCrossSubArray(A, low, mid, high);
if(rst_left[2]>=rst_right[2]&&rst_left[2]>=rst_cross[2])
return rst_left;
else if(rst_right[2]>=rst_left[2]&&rst_right[2]>=rst_cross[2])
return rst_right;
else
return rst_cross;
}
}
template<typename T>
vector<T> FindMaxSubArray(const vector<T>& A){
vector<T> tmp={0,0,A[0]};
for(int i=0; i<A.size()-1; ++i){
T left_sum=-9999999;
T sum=0;
int max_left=i;
for(int j=i+1; j>=0; --j){
sum += A[j];
if(sum>left_sum){
left_sum=sum;
max_left=j;
}
}
if(tmp[2]<left_sum){
tmp[0]=max_left;
tmp[1]=i+1;
tmp[2]=left_sum;
}
}
return tmp;
}