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];
}

Ideas:

Dynamic programming, just pay attention to different situations, such as all negative numbers / there is a 0 + remaining negative numbers / the previous subsum is 0, and it does not participate in the calculation of the subsequent sequence.

Note that it is not the output subscript, but the number corresponding to the following table.

Guess you like

Origin blog.csdn.net/u012571715/article/details/113901015