[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 ```cpp 10 -10 1 2 3 4 -5 -23 3 7 -21 ``` ### Sample Output ```cpp 10 1 4 ```

Solution

Analysis

题目要求计算给出的一个序列中最大的连续子序列和。
一个个累加,如果“临时最大和”大于“最大和”,那么更新“最大和”的信息,包括首位置和末位置的信息;如果“临时最大和”小于0的话,那么将临时首位置标记修改为当前位置,然后重新将“临时最大和”赋值为0,因为如果小于0的话,在以后的序列中,只会减少序列的和。
语言组织太乱,建议参考别人的 :柳婼 の 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;
	}
}
posted @ 2019-09-01 06:35  by-sknight  阅读(107)  评论(0编辑  收藏  举报