Maximum Subsequence Sum
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
题意:求最大连续子序列列和,输出最大的和以及这个子序列的开始值和结束值。如果所有数都小于0,那么认为最大的和为0,并且输出首尾元素~
思路:sum为要求的最大和,temp 为临时最大和,leftin 和 right 为所求的子序列的下标, t 标记 left 的临时下标~
temp = temp + a[i],当 temp 比 sum 大时,就更新 sum 的值、left 和 right 的值;当 temp < 0,那么后面不管是正数还是负数,都应该舍弃 temp < 0 前面的内容,因为负数对于总和只可能拉低总和,不可能增加总和,还不如舍弃~~ 舍弃后,直接令temp = 0,并且同时更新 left 的临时值 temp。
因为对于所有的值都为负数的情况要输出0,第一个值,后一个值,此时最大和 sum 一定为负数,所以要把 sum 变为 0 再输出,临时最大和 temp 也一定为负数,此时 left 和 right 没有进行更新,还是输入序列的首位,直接输出即可;
c++代码:
#include<iostream>
using namespace std;
int main(){
int n;
cin >> n;
int left=0, right=n-1, t, sum=-1, temp=0;
int a[n];
for(int i = 0; i < n; i++){
cin >> a[i];
temp += a[i];
if(temp < 0){
temp = 0;
t = i+1;
}
else if(sum < temp){
sum = temp;
left = t;
right = i;
}
}
if(sum < 0) sum = 0;
cout << sum << " " << a[left]<< " " << a[right];
return 0;
}
Python代码:
if __name__ == "__main__":
num = int(input())
line = input().split(" ")
number = [int(x) for x in line]
flag = True
if len([x for x in number if x >= 0]) == 0:
flag = False
print(0, number[0], number[-1])
sums = -1
temp, tempLeft, index, right, left = 0, 0, 0, 0, 0
if flag == True:
while(index != len(number)):
temp = temp + number[index]
index += 1
if temp < 0:
temp = 0
tempLeft = index
elif temp > sums:
sums = temp
left = tempLeft
right = index - 1
print(sums, number[left], number[right])