# PAT Advanced 1007 Maximum Subsequence Sum

2021-01-23 21:10:18 tanknee

# 题目

## 1007 Maximum Subsequence Sum (25分)

Given a sequence of K integers { N1, N2, ..., N**K }. A continuous subsequence is defined to be { N**i, N**i+1, ..., N**j } where 1≤ijK. 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 Specification:

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

### Output Specification:

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 Input:

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

### Sample Output:

``````10 1 4
``````

# 理解与算法

## 代码实现

``````#include <iostream>
#include <vector>

using namespace std;
int main() {
int count;
cin >> count;
vector<int> v(count);
// 最大值默认为-1，方便后面判断有没有找到最大值
// 左右下标初始值为整个数组的左右下标！
int max = -1, temp_max = 0, temp_index = 0, left = 0, right = count - 1;
for (int i = 0; i < count; ++i) {
cin >> v[i];
temp_max += v[i];
// 如果和已经小于零了，那么再往下走肯定不会是最大子序列！
if (temp_max < 0) {
// 重置临时最大值变量
temp_max = 0;
// 然后将下标移动到下一个值
temp_index = i + 1;
} else if (temp_max > max) {
// 如果找到了一个更大的和，就记录这个最大值和左右下标，因为起伏不定所以左下标会一直变化，就使用temp_index来作为下标
max = temp_max;
left = temp_index;
right = i;
}
}
// 如果最大值小于0，那么说明没找到大于0的最大值，就将其置为0！
if (max < 0) max = 0;
cout << max << " " << v[left] << " " << v[right];
return 0;
}
``````

https://www.cnblogs.com/tanknee/p/14318993.html