1007. Maximum Subsequence Sum (25)(java版)

Given a sequence of K integers { N1, N2, …, NK }. A continuous subsequence is defined to be { Ni, Ni+1, …, Nj } where 1 <= i <= j <= K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.

Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.

Input Specification:

Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (<= 10000). The second line contains K numbers, separated by a space.

Output Specification:

For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.

Sample Input:
10
-10 1 2 3 4 -5 -23 3 7 -21
Sample Output:
10 1 4

思路:

动态规划,就是判断是否应该将下一个数字加入到当前的序列中还是将下一个数字当成一个新的序列,假设第一个数字“-10”是第一个序列 S1 ,那么判断是否应该将第二个数字“1”加入到序列 S1 还是第二个数字为第二个序列 S2 ,明显当 S1 + “1” 后比“1”小,那么“1”就作为第二个序列 S2 的第一个数,然后判断第三个数“2”, 明显 S2 + “2”后大于 “2”所以“2”属于 S2 , 然后不断更新 max 的值,就可以得到答案。不知道为什么,第一次写的有一个测试点不过,网上找了很多java的代码,也都不过,后来发现ans的值初始化为0,瞬间感觉自己好笨。

代码:

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        int s = 0, e = 0;
        int ans1 = 0, ans2 = 0;
        int temp = 0, ans = -1000;
        int a1 = 0, a2 = 0;
        int dp = -1000;
        for(int i=0;iif(i == 0) {
                s = temp;
            }
            if(i == n-1) {
                e = temp;
            }
            if(dp + temp < temp) {
                dp = temp;
                a1 = a2 = temp;
            }
            else {
                dp += temp;
                a2 = temp;
            }
            if(dp > ans) {
                ans = dp;
                ans1 = a1;
                ans2 = a2;
            }
        }
        if(ans < 0) {
            System.out.println("0 " + s + " " + e);
        }
        else {
            System.out.println(ans + " " + ans1 + " " + ans2);
        }
    }
}

你可能感兴趣的:(1007. Maximum Subsequence Sum (25)(java版))