Problem Description
求一串字符序列中和最大的子序列。动态规划的经典例子。
输入的第一行 T(1<=T<=20) 表示有几组测试数据。就是有几串数据。
以后的每一行的第一个数 N(1<=N<=100000),表示该组数据中有几个数,即该串数据的长度。后面的数是测试数据,每个数据范围 (-1000 到 1000)
Output
每一组测试数据的答案前面都要输出一行"Case #:",# 代表行号,从1开始。下一行由三个数字组成,分别是子序列的和 开始位置 结束位置。如果有多个相同答案,输出第一个答案。
code
import java.util.*;
import java.io.*;
import java.math.*;
public class HDOJ1003{
public static void main(String[] args) throws Exception{
Scanner cin = new Scanner(System.in);
int count = cin.nextInt();
int mCase = 1;
while(count != 0)
{
int length = cin.nextInt();
long maxSum = -1001;
long thisSum = 0;
int start = 0;
int end = 0;
int tempIndex = 0;
for(int i = 0;i<length;i++){
thisSum += cin.nextInt();
if(thisSum>maxSum){
maxSum = thisSum;
end = i;
start = tempIndex;
}
if(thisSum<0){
tempIndex = i+1;
thisSum = 0;
}
}
System.out.println("Case "+mCase+":");
System.out.println(maxSum +" "+(start+1)+" "+(end+1));
mCase++;
count--;
if(count!=0)
System.out.println();
}
}
}