Max Sum

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
 
AC代码:
 1 import java.util.Scanner;
 2 
 3 public class Main {
 4 
 5     public static void main(String[] args) {
 6         Scanner sc = new Scanner(System.in);
 7         int n = sc.nextInt();   //输入测试次数
 8         int temp = 1;
 9         int startIndex = 1;     //开始位置
10         int endIndex = 1;        //结束位置
11         int sum = 0;            //12         //设置max为最小负数
13         int max = -0xfffffff;
14         for (int i = 0; i < n; i++) {
15             int m = sc.nextInt();     //输入数的个数
16             for (int j = 0; j < m; j++) {
17                 sum += sc.nextInt();
18                 if (sum > max) {   //当输入的所有数之后就是最大值时
19                     max = sum;
20                     startIndex = temp;
21                     endIndex = j + 1;
22                 }
23                 //这里不能用else if 因为当输入的数包含负数和零时,只会执行上面的if
24                 if (sum < 0) {
25                     sum = 0;
26                     temp = j + 2;
27                 }
28             }
29             System.out.println("Case " + (i + 1) + ":");
30             System.out.println(max + " " + startIndex + " " + endIndex);
31 
32             sum = 0;   
33             max = -0xfffffff;
34             startIndex = 1;
35             endIndex = 1;
36             temp = 1;
37             if (i != n - 1) {
38                 System.out.println();
39             }
40         }
41     }
42 }

 

 
posted @ 2017-12-13 16:03  ixummer  阅读(142)  评论(0编辑  收藏  举报