The Problem description is a sequence of {N1, N2,..., nk} Given K integers. Any continuous subsequence can be represented as {Ni, Ni + 1 ,...,
NJ}, where 1 <= I <= j <= K. The maximum continuous subsequence is the element and the largest of all consecutive subsequences,
For example, for a given sequence {-2, 11,-4, 13,-5,-2}, its maximum continuous subsequence is {11,-4, 13}, the largest and
Is 20.
In this year's data structure examination paper, the maximum sum of programming requirements is required. Now, a requirement is added, that is,
The first and last elements of the subsequence.
The input test input contains several test cases. Each test case occupies two rows, Row 1 provides a positive integer k (<1st), and row 3 provides K integers, separated by spaces. When K is 0, the input ends and the case is not processed.
For each test case, output the first and last elements of the largest sum and maximum continuous subsequences in one row.
, Separated by spaces. If the maximum continuous subsequence is not unique, the smallest sequence numbers I and j are output (for example, 2nd and 3 groups in the input sample ). If all k elements are negative, the maximum value is 0, and the first and last elements of the entire sequence are output.
Sample Input
6-2 11 -4 13 -5 -210-10 1 2 3 4 -5 -23 3 7 -2165 -8 3 2 5 01103-1 -5 -23-1 0 -20
Sample output
20 11 1310 1 410 3 510 10 100 -1 -20 0 0HintHint
Idea: first DP to find the largest continuous subsequence, then push (ADD) forward from the largest DP location to get the first position
Clearer code
# Include <iostream> # include <cstring> # include <cstdio> # include <algorithm> using namespace STD; # define n 10005int DP [N], a [n]; int main () {int I, n; while (scanf ("% d", & N), n) {int flag = 0; for (I = 1; I <= N; I ++) {scanf ("% d", & A [I]); if (a [I]> = 0) Flag = 1 ;} if (flag = 0) // A array is negative {printf ("0% d % d \ n", a [1], a [n]); continue ;} DP [1] = A [1]; for (I = 2; I <= N; I ++) {If (DP [I-1] <0) // understand DP [I] = A [I]; else DP [I] = DP [I-1] + A [I];} int Pos = 1; for (I = 2; I <= N; I ++) if (DP [I]> DP [POS]) // note that yes>, locate the smallest endpoint Pos = I; // find the maximum DP position int S, temp = 0; for (I = Pos; I> = 1; I --) {temp + = A [I]; If (temp = DP [POS]) // note that it is not break, because the minimum start point of the question is S = I ;} printf ("% d \ n", DP [POS], a [s], a [POS]);} return 0 ;}