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
Author
Ignatius.L
本題求解的是最大子段問題,也就是說從任何一個數開始,連續的中間不能間斷,幾個數都可以,把這些數加在一起求出最大值,然后返回這個最大值,并且返回初始下標和終止的下標。
這道題原本是筆者數據結構課上的一道題,我當初做出來的時候,那個高興啊,沒想到在acm里原來是道水題,O(∩_∩)O哈哈哈~,這道題采用暴力求解,分治算法都是可以解決的,當然最好的思想還是動態規劃的做法,時間負責度僅為O(n),在一次循環中動態更新最大值和起始下標與終止下標就可以實現啦。
代碼:
import java.util.Scanner;
public class Main1003 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T, N, num, startP = 1, endP = 1;
T = in.nextInt();
int m = T;
while (T-- > 0) {
int max = -1001, temp = 1, sum = 0;
N = in.nextInt();
for (int i = 1; i <= N; i++) {
num = in.nextInt();
sum += num;
if (sum > max) {
max = sum;
startP = temp;
endP = i;
}
if (sum < 0) {
sum = 0;
temp = i + 1;
}
}
System.out.println("Case " + (m - T) + ":");
System.out.println(max + " " + startP + " " + endP);
if (T != 0) {
System.out.println("");
}
}
}
}