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. 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 (≤). 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
方法一:
分析:sum为要求的最大和,temp为临时最大和,left和right为所求的子序列的下标,index标记left的临时下标~
temp = temp + v[i],当temp比sum大,就更新sum的值、left和right的值;当temp < 0,那么后面不管来什么值,都应该舍弃temp < 0前面的内容,因为负数对于总
和只可能拉低总和,不可能增加总和,还不如舍弃~舍弃后,直接令temp = 0,并且同时更新left的临时值tempindex。
1 int K; 2 cin >> K; 3 vector<int>v(K); 4 int l = 0, r = K - 1, sum = -1, temp = 0, index = 0;//所求的左、右边界,累加和,以及临时的累加和、左边界 5 for (int i = 0; i < K; ++i) 6 { 7 cin >> v[i]; 8 temp += v[i]; 9 if (temp < 0)//如果和小于0,则直接抛弃 10 { 11 temp = 0; 12 index = i + 1;//选下一个点为新左点 13 } 14 else if (temp > sum)//获得更大值 15 { 16 sum = temp; 17 l = index; 18 r = i; 19 } 20 } 21 if (sum < 0) 22 sum = 0; 23 cout << sum << " " << v[l] << " " << v[r] << endl;
方法二:
从数组的最后向前算:
当n + 1位置的最大累加和为正数时,那么n的最大累加和一定是自己加上n + 1的最大累加和,其最右边界与n + 1的最右边界相同
当n + 1位置的最大累加和为负数时,那么n的最大累加和一定是自己,因为再向后面加也是加一个负数,其最右边界就是自己的位置
1 int K; 2 cin >> K; 3 vector<int>v(K); 4 int l = 0, r = K - 1, sum = -1;//所求的左、右边界,累加和,以及临时的累加和、左边界 5 for (int i = 0; i < K; ++i) 6 cin >> v[i]; 7 8 vector<int>max_sum(K), max_sum_index(K);//当前数能获得最大值的到达的最右端 9 for (int r = K - 1; r >= 0; --r)//c从最右端开始加,每次得到自己获取最大值的最优边界 10 { 11 if (r + 1 < K && max_sum[r + 1] > 0)//加上大的数会使我变大 12 { 13 max_sum[r] = max_sum[r + 1] + v[r]; 14 max_sum_index[r] = max_sum_index[r + 1];//记录,我这边能到达的最右边是哪 15 } 16 else//加上负数会使我变小,还不如自己当最大的数 17 { 18 max_sum[r] = v[r]; 19 max_sum_index[r] = r; 20 } 21 } 22 for (int t = 0; t < K; ++t) 23 { 24 if (max_sum[t] > sum) 25 { 26 sum = max_sum[t]; 27 l = t;//自己为左边界 28 r = max_sum_index[t];//记录点为右边界 29 } 30 } 31 if (sum < 0)//如果最大和小于0,则所有数都小于0,按要求输出整个数组 32 { 33 sum = 0; 34 l = 0; 35 r = K - 1; 36 } 37 cout << sum << " " << v[l] << " " << v[r] << endl;
原文地址:https://www.cnblogs.com/zzw1024/p/11172958.html