01-复杂度2 Maximum Subsequence Sum (25分)
Given a sequence of K integers { N1 , N2, …, NK}.Acontinuoussubsequence 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
题目有点坑啊,我写完以后一直有一个错误:并列和对应相同i但是不同j,即尾是0。
改了好久才改出来。原来是序列前0的情况,要从0开始算起,因为要求的是最小的 i 和 j 。
出现这个问题的可以用这几个例子验证:
输入:-1 -2 -3 0 -5
输入:0 0 0
输入:0 1 2 3
输出:6 0 3
输入:-2 0 0 1 0
输出:1 0 1
AC代码:
#include <iostream>
using namespace std;
int main() {
int k;
cin >> k;
int Num[k];
int flag = 1 ,min = 0;
for (int i = 0; i < k; i++) {
cin >> Num[i];
if (Num[i] >= 0) flag = 0;
else if (Num[i] < 0) min += Num[i]; //所以负相加得到一个最小的值
}
if (flag) { //全是负数
cout << '0' << ' ' << Num[0] << ' ' << Num[k-1];
return 0;
}
int sum = 0, max = min;
//重点在于给max一个在序列中最小的初值,在序列中遇到负数,rear和front也会继续随前进,直到遇到0或正数。
int rear = 0, front = 0, temp = 0;
for (int i = 0; i < k; i++) {
sum += Num[i];
if (sum > max) { //找到更大的值,重新赋值一下
rear = i;
front = temp;
max = sum;
}
if (sum < 0) { //负值直接去掉
temp = i + 1;
sum = 0;
}
}
cout << max << ' ' << Num[front] << ' ' << Num[rear];
return 0;
}
在线处理法