杭電oj-1003(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

Author

Ignatius.L

本題求解的是最大子段問題,也就是說從任何一個數(shù)開始,連續(xù)的中間不能間斷,幾個數(shù)都可以,把這些數(shù)加在一起求出最大值,然后返回這個最大值,并且返回初始下標和終止的下標。

這道題原本是筆者數(shù)據(jù)結(jié)構(gòu)課上的一道題,我當初做出來的時候,那個高興啊,沒想到在acm里原來是道水題,O(∩_∩)O哈哈哈~,這道題采用暴力求解,分治算法都是可以解決的,當然最好的思想還是動態(tài)規(guī)劃的做法,時間負責度僅為O(n),在一次循環(huán)中動態(tài)更新最大值和起始下標與終止下標就可以實現(xià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("");
            }
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容