PAT 1007 Maximum Subsequence Sum
1007 Maximum Subsequence Sum
Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, Ni+1, ..., Nj } where 1≤i≤j≤K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.
Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.
Input Specification:
Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (≤10000). The second line contains K numbers, separated by a space.
Output Specification:
For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.
Sample Input:
10
-10 1 2 3 4 -5 -23 3 7 -21
Sample Output:
10 1 4
自己写的代码:一开始只写了13分,没有考虑到只有一个整数的情况,没有更新sum,max,min的值,但是现在还是没有满分,以后慢慢琢磨 (知道错哪里了)
例子:
2
0 -1
正确答案应该是 0 0 0 因为0是非负数,所以0在这里算是最大值
而不是这个代码打印出来的 0 0 -1
解决办法:sum一开始的赋值应该为-1,让当a[i]=0的情况也能更新 l, r
代码:
#include <iostream>
using namespace std;
const int N=10010;
int f[N];
int a[N];
int n;
int main(){
cin >> n;
int min=0,max=0,sum=0,l=0,r=0;
int sign=0;
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
if(a[i]>=0) sign=1;//此处大于等于0才算是非负数
}
if(!sign) printf("0 %d %d\n",a[1],a[n]);
else{
for(int i=1;i<=n;i++){
//目前想到的当f[i-1]<=0时,就可以直接放弃前面的数了
//或者和当前一个负数相加<=0,也可以直接放弃
//还有情况是一个数组中只有一个负数时,-1 -2 3 -5,这时也需要改变sum,l,r的值
if(f[i-1]<=0){
f[i]=a[i];
l=i;
if(f[i]>sum){
sum=f[i];
min=l;
max=l;//这里要注意的是因为当前r还未更新,所以r<=i,只能手动给max赋值
}
}
else{
f[i]=f[i-1]+a[i];
r=i;
if(f[i]>sum){
sum=f[i];
min=l;
max=r;
}
}
}
printf("%d %d %d\n",sum,a[min],a[max]);
}
return 0;
}
依照惯例,还是看看大佬的代码:
思路简单明了,清晰易懂
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
scanf("%d", &n);
vector<int> v(n);
int leftindex = 0, rightindex = n - 1, sum = -1, temp = 0, tempindex = 0;
for (int i = 0; i < n; i++) {
scanf("%d", &v[i]);
temp = temp + v[i];
if (temp < 0) {
temp = 0;
tempindex = i + 1;
} else if (temp > sum) {
sum = temp;
leftindex = tempindex;
rightindex = i;
}
}
if (sum < 0) sum = 0;
printf("%d %d %d", sum, v[leftindex], v[rightindex]);
return 0;
}
只需要存前面是大于0的状态,小于0的直接舍弃,果断一点
好好学习,天天向上!
我要考研!