1007 Maximum Subsequence Sum (25 point(s))

1007 Maximum Subsequence Sum (25 point(s))

Given a sequence of K integers { N​1​​, N​2​​, ..., N​K​​ }. A continuous subsequence is defined to be { N​i​​, N​i+1​​, ..., N​j​​ } 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.

Example:

#include<iostream>
#include<vector>

using namespace std;

int main()
{
    int K;
    cin >> K;
    vector<int> Seq(K);
    for(int i = 0; i < K; i++)
        cin >> Seq[i];
    int Max = -1, First, Last;
    for(int i = 0; i < K; i++) {
        int ans, first, last, temp;
        if(Seq[i] == 0) {
            if(Max == -1) 
                Max = 0, First = Last = i;
        } else if(Seq[i] > 0) {
            ans = -1;
            temp = 0;
            first = i;
            for(; i < K; i++) {
                temp += Seq[i];
                if(temp < 0) break;
                if(temp > ans)
                    ans = temp, last = i;
            }
            if(ans > Max)
                Max = ans, First = first, Last = last;
        }
    }
    if(Max == -1)
        Max = 0, First = 0, Last = K - 1;
    cout << Max << ' ' << Seq[First] << ' ' << Seq[Last];
}

思路:

动态规划,只是要注意到不同情况,比如全是负数/有一个0+剩余负数/前面一个子和为0,不参与后面序列的计算。

注意不是输出下标,而是下表对应的数。

猜你喜欢

转载自blog.csdn.net/u012571715/article/details/113901015
今日推荐