Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 141614 Accepted Submission(s): 32953
Problem Description
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.
Input
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).
Output
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.
Sample Input
2 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -5
Sample Output
Case 1: 14 1 4 Case 2: 7 1 6/* * 典型动态规划的思想 动态规划的经典题 之前我一直不是很理解动态规划 * 我个人做题的时候 遇到动态规划的题型 直接用递归 * 算法分析:求最大字段和,d[i]表示在已i结尾(包含i)在a[1...i]上的最大和,d[i]=(d[i-1]+a[i]>)?d[i-1]+a[i]:a[i]; * max={d[i],n>=i>=1} * * */ import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in =new Scanner(System.in); final int N=100010; //注意定义多一些 开始我定义少了 提交三次都是WA int[] a =new int[N]; int[] d=new int[N]; int ee=0; int test=in.nextInt(); for(int j=0;j<test;j++){ int x=in.nextInt(); for(int y=1;y<=x;y++){ a[y]=in.nextInt(); } d[1]=a[1]; for(int m=2;m<=x;m++)// 动态规划的核心 { if(d[m-1]<0) d[m]=a[m]; else d[m]=d[m-1]+a[m]; } int max=d[1],e=1; for(int a1=2;a1<x+1;a1++)//找出最右边的点 { if(max<d[a1]) { max=d[a1]; e=a1; } } int t=0,f=e; for(int i=e;i>0;i--)//找出最左边的点 { t=t+a[i]; if(t==max) f=i; } System.out.println("Case "+(j+1)+":"); System.out.println(max+" "+f+" "+e); ee++; if(ee!=test) System.out.println(); } } }