[PTA] PAT(A) 1007 Maximum Subsequence Sum (25 分)

Problem

portal: 1007 Maximum Subsequence Sum (25 分)

Description

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 \leq i \leq j \leq 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

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

Output

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

Sample Input

10
-10 1 2 3 4 -5 -23 3 7 -21

Sample Output

10 1 4

Solution

Analysis

Title requires the largest contiguous sequence and a given sequence is calculated.
An accumulative, if the "interim maximum and" greater than "and maximum", the updated "maximum and" the information, including the first position and the end position; if the "temporary maximum and" less than 0, then the temporary first position mark modify the current position, and then reinstall the "largest and temporary" assignment to 0, because if less than 0, then later in the sequence, and the sequence will reduce.
Language organization too messy, others proposed reference: Liu recalcitrantのblog

Code

#include <bits/stdc++.h>
using namespace std;

int main(void) {
    int K, first_number, second_number, temp_first_number;
    long max_sum = -1, temp_max_sum = -1;

    cin >> K;
    int value[K];
    for (int i = 0; i < K; i++) {
        cin >> value[i];
        if (temp_max_sum < 0) {
            temp_first_number = value[i];
            temp_max_sum = 0;
        }
        temp_max_sum += value[i];
        if (temp_max_sum > max_sum) {
            max_sum = temp_max_sum;
            first_number = temp_first_number;
            second_number = value[i];
        }
    }
    if (max_sum == -1) {
        cout << "0 " << value[0] << " " << value[K - 1] << endl;
    } else {
        cout << max_sum << " " << first_number << " " << second_number << endl;
    }
}

Guess you like

Origin www.cnblogs.com/by-sknight/p/11441308.html