Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, Ni+1, ..., Nj } where 1. 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 iand 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
题目分析:输入一行数字,要用空格隔开,
输出格式:求出最大的子序列和,并且输出子序列和的第一个数和最后一个数。
注意:要是全为负数的话,就输出总和为0,并且输出第一个数字和最后一个数字。
求第一个数字和最后一个数字的时候,可以先记住最后一个数字的下标,然后再逆推求和,跟最大值比对,相等的话就更新第一个数字的下标。因为-10,5,-5,1,2,3,4,-5,-10的话输出的应该是10 5 4,不应该是10 1 4。
代码如下 :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
int thisHalf = 0,maxHalf = 0;
int firstNum = 0,lastNum = 0;
int temp = 0;
int[] a = new int[k];
for(int i = 0;i < k;i++) { //用数组保存键盘输入的值
a[i] = sc.nextInt();
}
for(int j = 0;j < k;j++) {
thisHalf += a[j];
if(thisHalf > maxHalf) {
lastNum = j; //保存最大子序列和的第二个数的下标
maxHalf = thisHalf;
}
else if(thisHalf < 0 ) {
thisHalf = 0;
}
}
for(int i = lastNum;i >= 0;i--) { //逆推回来求最大序列和的第一个数的下标
temp += a[i];
if(temp == maxHalf) {
firstNum = i;
}
}
if(maxHalf == 0) {
System.out.println(maxHalf+" "+a[0] +" "+a[k-1]);
}else if(maxHalf > 0){
System.out.println(maxHalf+" "+a[firstNum]+" "+ a[lastNum]);
}
}
}