您的位置:首页 > 编程语言 > Java开发

java 基础编程 HDOJ Max Sum

2014-05-22 19:38 281 查看

Max Sum

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 137152 Accepted Submission(s): 31781



[align=left]Problem Description[/align]
Given a sequence a[1],a[2],a[3]......a
, 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.

[align=left]Input[/align]
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).

[align=left]Output[/align]
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.

[align=left]Sample Input[/align]

2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5


[align=left]Sample Output[/align]

Case 1:
14 1 4

Case 2:
7 1 6
AC代码:注意归零操作与更新子序列初始与结束下标

[code]package com.ACM;

import java.util.Scanner;

public class SubStringSum {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);
int n = in.nextInt();
int count = 1;
while(count <= n){
int number = in.nextInt();
int[] array = new int[number];

for(int i=0; i<number; i++){
array[i] = in.nextInt();
}

int nStart = array[0];
int startTemp = 1;
int start = 1;
int end = 1;
int nAll = array[0];

for(int i=1; i<number; i++){
if(nStart < 0){
startTemp = i+1;
nStart = 0;<span style="white-space:pre">	</span>//归零操作
}
nStart += array[i];
if(nStart > nAll){
start = startTemp;<span style="white-space:pre">	</span>//更新起始下标
end = i+1;<span style="white-space:pre">	</span>//更新结束下标
nAll = nStart;
}
}

System.out.println("Case "+count+":");
System.out.println(nAll+" "+start+" "+end);
if(count != n){
System.out.println();
}
count++;
}

}

}


[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: