Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, Ni+1, ..., Nj } where 1≤i≤j≤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 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>
using namespace std;
#include<string>
#include<algorithm>
#pragma warning (disable:4996)
#include <climits>
int arr[10000];
int main() {
int K;
cin >> K;
int temp = 0, sum = -1;
int i = 0, j = K - 1, i_temp=0;
for (int cnt = 0; cnt < K; cnt++) {
cin >> arr[cnt];
temp += arr[cnt];
if (temp < 0) {
temp = 0;
i_temp = cnt + 1;
}
else if (temp > sum)
{
sum = temp;
i = i_temp;
j = cnt;
}
}
if (sum < 0)cout << "0" <<" "<< arr[0] << " " << arr[K - 1];
else
{
cout << sum << " " << arr[i] << " " << arr[j];
}
return 0;
}
这道题的化简思路就是将一连串的数据看作一个数据,那么我们的问题就转化成了这一连串的数据中哪一个最大,由此就可以将问题转化为求最大值的问题.然后思考一连串的数据的加法问题,因为一个正数和一个负数相加,它们的和一定比正数小,由此可以得到一个加法的正数集合加上任意一个负数集合,它们的和一定减小,到了这里,我们就可以将temp的值重赋为0,再进行找另一个更大的加法集合.
#include<iostream>
using namespace std;
#include<string>
#include<algorithm>
#pragma warning (disable:4996)
#include <climits>
int arr[10000];
int main() {
int K;
cin >> K;
for (int cnt = 0; cnt < K; cnt++) {
cin >> arr[cnt];
}
int max_sum = INT_MIN, i=0, j=0, sum;
bool flag = 1;
for (int cnt = 0; cnt < K; cnt++) {
sum = arr[cnt];
for (int cnt1 = cnt + 1; cnt1 < K; cnt1++) {
sum += arr[cnt1];
if (max_sum < sum) {
max_sum = sum;
i = cnt; j = cnt1;
}
}
if (arr[cnt] > 0)flag = 0;
}
if (flag)cout << "0" <<" "<< arr[0] << " " << arr[K];
else cout << max_sum<<" "<< arr[i] << " " << arr[j];
return 0;
}
上面这种写法的错因是因为cnt+1以后有一个边缘条件也就是最后一个数字,它的值不会被录入,因为正好会等于K值,不满足题意了.其实遍历加和用for循环都有这种风险,这种风险的出现原因是因为我们的行为发生在内循环中,但内循环彻底结束时,外循环其实还是有有效值的