Given a sequence of K integers { , , …, }. A continuous subsequence is defined to be { , , …, } where . 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 (). 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
Solve
最大子序列和问题,有两种解法,一种贪心,一种DP。
贪心解法
维护最大子序列和的起点、终点和最大值。因为是只要最大的且若全是负数则默认最大和为0,故若当前连续和为负数时,其对后续累加是负贡献(因为必须要连续),则可以直接将其抛弃重新累加。
抛弃并不会导致最优结果丢失,因为如果最优结果在抛弃前存在,那么在累加当前值之前,就会被维护到并记录,直到后续处理中遇见更优值时被替换。
这样只在遇到更优时才替换的策略,也能保证最终记录的结果是最小下标。
#include<iostream>
#include<vector>
using namespace std;
const int INF = 0x3f3f3f3f;
int main() {
int n;
cin >> n;
vector<int> nums(n);
for(int i = 0; i < n;i ++)
cin >> nums[i];
int start = 0, end = n-1, res = -1, sum = 0, p = 0;
for(int i = 0; i < n; i++) {
sum += nums[i];
if(sum > res) {
res = sum;
start = p;
end = i;
}
if(sum < 0) {
p = i + 1;
sum = 0;
}
}
if(res < 0) res = 0;
cout << res << " " << nums[start] << " " << nums[end] << endl;
return 0;
}
DP 解法
状态定义:f[i]
为以 为结尾的最大子序和值, 为以 为结尾的最大子序和的最小下标。
状态转移:
- 如果
f[i-1] + nums[i] > nums[i]
,则延续前面的子序列:f[i] = f[i-1] + nums[i]
且p[i] = p[i-1]
- 否则,开始一个新的子序列:
f[i] = nums[i]
且p[i] = i
在整个过程中,我们追踪目前为止看到的最大和及其对应的起始和结束索引。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int k;
cin >> k;
vector<int> nums(k);
for (int i = 0; i < k; i++) {
cin >> nums[i];
}
vector<int> f(k); // 以索引 i 结尾的最大和
vector<int> p(k); // 以索引 i 结尾的最大子序列的起始索引
f[0] = nums[0];
p[0] = 0;
int maxSum = f[0];
int start = 0, end = 0;
for (int i = 1; i < k; i++) {
if (f[i-1] + nums[i] > nums[i]) {
f[i] = f[i-1] + nums[i];
p[i] = p[i-1];
} else {
f[i] = nums[i];
p[i] = i;
}
if (f[i] > maxSum) {
maxSum = f[i];
start = p[i];
end = i;
}
}
// 处理所有数字都为负数的情况
if (maxSum < 0) {
cout << "0 " << nums[0] << " " << nums[k-1] << endl;
} else {
cout << maxSum << " " << nums[start] << " " << nums[end] << endl;
}
return 0;
}