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题目大意:
这道题题目意思非常迷惑,原因是题目中有句话一直没理解对,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).有道上给出的翻译是:如果最大子序列不是唯一的,则输出索引i和j最小的子序列(如示例所示)。 我理解为:若果不唯一时,输出最小的索引i和j。。。忽略了the one,直接导致几个小时也没能AC,知道运行了网上正确的代码才慢慢读懂题意。参考了:LangWeiXian
题意为找出最大的子序列和,并输出子序列的首尾值。
解题思路:读懂题意非常关键,要设置临时和,临时首索引变量,要注意子序列的前后为0时的取舍,直接看代码注释吧。
java代码:import java.io.*;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] split = br.readLine().split(" ");
int []arr = new int[n];
boolean flag = true;
for(int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(split[i]);
if(arr[i] >= 0) {
flag = false;
}
}
if(flag) {//均为负数
System.out.print("0 ");
System.out.println(arr[0] + " " + arr[n - 1]);
System.exit(0);
}
int finMax = Integer.MIN_VALUE;//最终和,开始假设最小
int start = 0;//最终开始索引
int end = n - 1;//最终结束索引
int index = 0;//临时开始索引
int tempMax = 0;//临时和
for(int i = 0; i < n;i++) {
tempMax += arr[i];
if(tempMax >= 0) {//要琢磨题意,索引最小
if(tempMax > finMax) {//要保证最前面的和,防止后面还有一样和时,索引变大
finMax = tempMax;
if(start != index) {
start = index;//更换开始索引
}
end = i;//只要当前值满足条件,就将当前值设为最后值
}
}else {
index = i + 1;//若为负值时,直接将临时索引置于下一元素
tempMax = 0;//同时临时和归零
}
}
System.out.println(finMax + " " + arr[start] + " " + arr[end]);
}
}
PAT提交截图:
机器测试数据:



