一、题目
Given a sequence of integers . A continuous subsequence is defined to be where . 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. The second line contains 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 and (as shown by the sample case). If all the 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>
using namespace std;
int main() {
int k = 0;
cin >> k;
int *n = new int[k];
int b = 0, sum = 0;
int l = 0, l1 = 0, r = 0, r1 = 0;
for (int i = 0; i < k; ++i) {
cin >> n[i];
if (b > 0) {
b += n[i];
r = i;
} else {
b = n[i];
r = i;
l = i;
}
if (b > sum) {
sum = b;
l1 = l;
r1 = r;
} else if (b == 0 && sum == 0) {
l1 = l;
r1 = r;
}
}
if (l1 == 0 && r1 == 0 && b < 0)
cout << sum << " " << n[0] << " " << n[k - 1];
else
cout << sum << " " << n[l1] << " " << n[r1];
}
四、注意事项
坑点是:当全为负数时,输出0 首 尾;当有0,其余为负时,应输出0 0 0。
网友评论