Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 260585 Accepted Submission(s): 61936
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
翻译:就是几个int数,按序拜访 如6 -1 5 4 -7 找到其中连续的几个数 使得和为最大(不一定要从第一个数头开始)
第一个数是代表这个数组有几个 后面是具体的数
public class MaxSum1003 { private static List<Integer> list; private static int begin = 0; private static int end = 0; private static int max = 0; public static void main(final String[] args) throws Exception { initData(); calculate(list); System.out.println("" + max + (begin+1) + (end+1)); } private static void initData() { list = new ArrayList<>(); list.add(6); list.add(-1); list.add(5); list.add(4); list.add(-7); } private static void calculate(List<Integer> list) { int size = list.size(); int sum = 0; //如果固定从头开始,直接开始累加,不断和最大值比较 // for (int i = 0; i < size; i++) { // sum += list.get(i); // max = Math.max(sum, max); // } //如果不一定要从头开始,就是本题情况,从一串数中,截取一段,需要是和最大 //这里和上面唯一的区别是需要加个if来判断,是否舍弃前面的东西 for (int i = 0; i < size; i++) { sum += list.get(i); if (sum > max) { max = sum; end = i; } //如果前面的sum和小于0了,还要他干什么,所以舍弃 if (sum < 0) { sum = 0; begin = i; } } } }