算法:
struct Seq{
int sum;
int startIndex;
int endIndex;
};
Seq maxSubSum4(const vector<int> & a)
{
int thisSum = 0;
int startIndex =0;
int temp = 0;
int endIndex = 0;
int maxSum = a[0];
for(int j=0;j<a.size();j++){// //如果序列全为负数,直接找最大的负数
if(maxSum < a[j]){
maxSum = a[j];
endIndex = j;
startIndex = endIndex;
}
}
if(maxSum >0){//序列为正负数(且maxSum大于0)或者全是正数
for(int j=0;j<a.size();j++){
if(thisSum<0){ //需要丢弃此序列,重新寻找新的连续序列,负数加任何数都是副作用
thisSum = 0;
temp = j;
}
thisSum+=a[j]; //Sum(i, j+1) = Sum(i, j) + A[j+1]
if(thisSum > maxSum){
maxSum = thisSum;
startIndex = temp;//新的开始,也就是起始坐标
endIndex = j;
}
}
}
Seq maxSeq;
maxSeq.sum = maxSum;
maxSeq.startIndex = startIndex;
maxSeq.endIndex = endIndex;
return maxSeq;
}
Seq minSubSum4(const vector<int> & a)
{
int thisSum = 0;
int startIndex =0;
int temp = 0;
int endIndex = 0;
int minSum = a[0];
for(int j=0;j<a.size();j++){// //如果序列全为正数,直接找最大的正数
if(minSum > a[j]){
minSum = a[j];
endIndex = j;
startIndex = endIndex;
}
}
if(minSum < 0){//序列为正负数(且minSum小于0)或者全是负数
for(int j=0;j<a.size();j++){
if(thisSum > 0){
thisSum = 0;
temp = j; //新的开始,也就是起始坐标
}
thisSum+=a[j]; //Sum(i, j+1) = Sum(i, j) + A[j+1]
if(thisSum < minSum){
minSum = thisSum;
startIndex = temp;
endIndex = j;
}
}
}
Seq minSeq;
minSeq.sum = minSum;
minSeq.startIndex = startIndex;
minSeq.endIndex = endIndex;
return minSeq;
}
测试
vector<int> arr1 = {4,-1,5,-2,-1,2,6,-2,-1,5,-2,-1};
vector<int> arr2 = {9,-3,-5,-7,11,7};
vector<int> arr3 = {-3,-3,-7,-2,-5};
vector<int> arr4 = {3,-2,5,-7,9,-6,-7,-3,2,10};
vector<int> arr5 = {20,3,-10,2,-32,14,5,6,-7};
结果
最大子序列的和为 15 startIndex is 0 endIndex is 9
最大子序列的和为 18 startIndex is 4 endIndex is 5
最大子序列的和为 -2 startIndex is 3 endIndex is 3
最大子序列的和为 12 startIndex is 8 endIndex is 9
最大子序列的和为 25 startIndex is 5 endIndex is 7
最小子序列的和为 -3 startIndex is 3 endIndex is 4
最小子序列的和为 -15 startIndex is 1 endIndex is 3
最小子序列的和为 -20 startIndex is 0 endIndex is 4
最小子序列的和为 -16 startIndex is 5 endIndex is 7
最小子序列的和为 -40 startIndex is 2 endIndex is 4
按 <RETURN> 来关闭窗口...