原题
Given a sequence of K integers . A continuous subsequence is defined to be 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
题目翻译
给定一个由 K 个整数组成的序列。连续子序列的定义是 ,其中 1 ≤ i ≤ j ≤ K。最大子序列是其元素之和最大的连续子序列。例如,给定序列 { -2, 11, -4, 13, -5, -2 },其最大子序列为 { 11, -4, 13 },最大和为 20。
现在你要找出最大和,以及最大子序列的第一个和最后一个数字。
输入规范:
每个输入文件包含一个测试用例。每个案例占两行。第一行包含一个正整数 K(≤10000)。第二行包含 K 个数字,用空格隔开。
输出规范:
对于每个测试用例,在一行中输出最大和,以及最大子序列的第一个和最后一个数字。这些数字必须用一个空格分隔,但行末不得有多余的空格。如果最大子序列不是唯一的,则输出下标 i 和 j 最小的子序列(如示例所示)。如果 K 个数字都是负数,那么其最大和定义为 0,您应该输出整个序列的第一个和最后一个数字。
解题思路
贪心,当sum小于0时将sum赋为0。本题需注意:
1.输出的为最大子序列的第一个和最后一个数字而不是下标。
2.(测试点5小坑)当且仅当所有数字全为负数时才输出整个序列的第一个和最后一个数字,即如果序列中包含0,则输出连续0的起始与结束下标,如输入(2, -1, 0)时,应输出(0, 0, 0)而不是(0, -1, 0)。
代码 (c++)
#include <bits/stdc++.h>
using namespace std;
const int N = 10010, INF = 0x3f3f3f3f;
int n, a[N];
int main(){
cin >> n;
for (int i = 0; i < n; i ++) cin >> a[i];
int ans = -INF, sum = 0, l = 0, r = 0, tmpl = 0; // l记录最大值的起始下标,r为终止下标,ans为负值即可,便于处理有0情况
for (int i = 0; i < n; i ++){
sum += a[i];
if (sum > ans) r = i, l = tmpl, ans = sum; // sum为新的最大值,更新l,r
if (sum < 0) sum = 0, tmpl = i + 1;
}
if (ans < 0) ans = 0, l = 0, r = n - 1;
cout << ans <<' '<< a[l] <<' '<< a[r] << endl;
return 0;
}