01-复杂度2 Maximum Subsequence Sum(25 分)
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
import java.util.Scanner;
public class Main{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int k =sc.nextInt();
int m[]=new int[k];
int sum = 0;
int tempMinIndex=0;
int minIndex=0;
int maxIndex=0;
for(int i =0;i<k;i++){
m[i] = sc.nextInt();
}
int thisMax=m[0];
for(int j=0;j<k;j++){
if(sum>=0){
sum+=m[j];
}
else{
sum=m[j];
tempMinIndex=j;
}
if(sum>thisMax){
thisMax = sum;
maxIndex=j;
minIndex=tempMinIndex;
}
if(thisMax<0){
thisMax=0;
minIndex=0;
maxIndex=k-1;
}
}
System.out.println(thisMax+" "+m[minIndex]+" "+m[maxIndex]);
}
}
提交结果
提交时间 | 状态 | 分数 | 题目 | 编译器 | 耗时 | 用户 |
---|---|---|---|---|---|---|
2018/4/4 21:17:03 | 部分正确 | 22 | 01-复杂度2 | Java (openjdk) | 109 ms | 风的追忆 |
测试点 | 提示 | 结果 | 耗时 | 内存 |
---|---|---|---|---|
0 | sample换1个数字。有正负,负数开头结尾,有并列最大和 | 答案正确 | 108 ms | 13228KB |
1 | 最大和序列中有负数 | 答案正确 | 105 ms | 16036KB |
2 | 并列和对应相同i但是不同j,即尾是0 | 答案正确 | 109 ms | 11472KB |
3 | 1个正数 | 答案正确 | 103 ms | 14284KB |
4 | 全是负数 | 答案正确 | 106 ms | 14332KB |
5 | 负数和0 | 答案错误 | 108 ms | 13164KB |
6 | 最大和前面有一段是0 | 答案正确 | 106 ms | 13256KB |
7 | 最大N | 运行超时 | 0 ms | 0KB |