Max-Sum(最大子序列)(简单dp入门)

题目:
Given a sequence a[1],a[2],a[3]…a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
输入:
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
输出:
For each test case, you should output two lines. The first line is “Case #:”, # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
样例输入:
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
样例输出:
Case 1:
14 1 4

Case 2:
7 1 6

import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();//样例数
		int o = 0;//用于后面的输出格式(Case o:)
		while (t-- > 0) {
			o++;
			int n = sc.nextInt();//数组长度
			int max = 0, h = 1, s = 1, b = 1;//max是最大子序列数值
			//h是最大子序列的右端索引,b,s是子序列的左端索引
			int a[] = new int[n + 1];
			for (int i = 1; i <= n; i++)
				a[i] = sc.nextInt();//赋值
				for (int i = 1; i <= n; i++) {//从1开始遍历数组
					if (a[i - 1] >= 0)//判断a[i-1]是否不小于0;
									//a[i-1]就是目前这个子序列前i-1项之和
									//如果大于0,a[i]+就会使变大,所以累加
						a[i] += a[i - 1];
					else//如果a[i-1]<0更新最大子序列下标
						b = i;
					if (max < a[i]) {//a[i]增加或者不变之后,判断是否大于max
					//max就是用于存放最大子序列的值
						max = a[i];
						h = i;//更新最大子序列的左右索引
						s = b;
					}
			}
			System.out.println("Case " + o + ":");
			System.out.println(max + " " + s + " " + h);
			if (o != t)
				System.out.println();
		}
	}
}

感觉也没错,样例和一些我能想到的特殊例子也能过,就是在网站上提交一直显示Wrong Answer;未能解决。。。。

你可能感兴趣的:(算法,笔记)