【题意】
求出给出的整数串中的最大和子串
【思路】
一个所求子串必然以非负整数开始,然后在右指针右移、不断地加上新数字的过程中要保证部分和非负,否则这个部分和就要舍弃,更新左指针。整个扫描过程中需要记录最大的部分和以及对应的最左、最右数值。
【注意点/易错点】
如果最大子串和为0,且不是因为全是负数而默认输出的0,那么输出的左右数值就不是整个数字串最左边和最右边的数字了,而是0,这一点需要特殊处理。
#include <iostream>
#include <vector>
using namespace std;
int main(){
//扫描过程中的工作左右下标
int workLeftIndex,workRightIndex;
//扫描过程中的最大子串对应的起始、终点数值
int maxLeft,maxRight;
int maxSum,sum,k,num;
vector<int> seq;
cin >> k;
for(int i=0; i<k; i++){
cin >> num;
seq.push_back(num);
}
maxSum = -1;
maxLeft = seq.at(0);
maxRight = seq.at(k-1);
workLeftIndex = workRightIndex = 0;
while(workLeftIndex<k){
while(workLeftIndex<k && seq.at(workLeftIndex)<0)
workLeftIndex++;
if(workLeftIndex>=k)
break;
sum = 0;
for(workRightIndex = workLeftIndex; workRightIndex<k && sum>=0; workRightIndex++){
sum += seq.at(workRightIndex);
if(sum>maxSum){
maxSum = sum;
maxLeft = seq.at(workLeftIndex);
maxRight = seq.at(workRightIndex);
}
}
workLeftIndex = workRightIndex;
}
if(maxSum>=0)
cout << maxSum;
else
cout << 0;
cout << " " << maxLeft << " " << maxRight;
system("pause");
return 0;
}