Given a sequence of KK integers {N1, N2,…, Nk}. A continuous subsequence is defined to be {Ni, N(i+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 KK (\le 10000≤10000). The second line contains KK 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 ii and jj (as shown by the sample case). If all the KK 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

Code

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def OnlineProcessing(lst, n):
ThisSum = MaxSum = 0
MinNum = TmpMin = lst[0]
MaxNum = lst[-1]

i = 0
while i < n:
ThisSum += lst[i]
# 如果当前和大于历史最大和,赋值给最大和。更新最小数字和最大数字
if ThisSum > MaxSum:
MaxSum = ThisSum
MinNum = TmpMin
MaxNum = lst[i]
# 如果当前和为负数,抛弃当前和,并将下一个数字作为最小数字备选。之后,如果有当前和大于历史最大和,则将此备选赋值给最小数字。
elif ThisSum < 0:
ThisSum = 0
if i < n - 1: # 当为最后一个数字时,不需要设最小数字备选,i+1 会超过列表范围。
TmpMin = lst[i + 1]
i += 1

# 当最大和为0时,要么全为负数,输出第一和最后一个数字;要么由负数和0组成,输出0。
if MaxSum == 0:
MinNum = lst[0]
MaxNum = lst[-1]
if 0 in lst:
MinNum = MaxNum = 0

print(str(MaxSum) + ' ' + str(MinNum) + ' ' + str(MaxNum))

def main():
n = int(input())
lst = input()
lst = [int(e) for e in lst.split()]
OnlineProcessing(lst, n)

main()

C

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include<stdio.h>

int main() {
const int N = 10000;
int A[N];
int n;
int ThisSum = 0, MaxSum = 0;
int MinNum, MaxNum, TmpMin;

scanf("%d", &n);

for ( int i = 0; i < n; i++ ) {
scanf("%d", &A[i]);
}

MinNum = TmpMin = A[0];
MaxNum = A[n-1];
for ( int i = 0; i < n; i++ ) {
ThisSum += A[i];
if ( ThisSum > MaxSum ) {
MaxSum = ThisSum;
MinNum = TmpMin;
MaxNum = A[i];
} else if ( ThisSum < 0 ) {
ThisSum = 0;
if ( i < n - 1) { //n-1为最后一个下标
TmpMin = A[i+1];
}
}
}

if ( MaxSum == 0 ) {
MinNum = A[0];
MaxNum = A[n-1];
for ( int i = 0; i < n; i++ ) {
if ( A[i] == 0 ) {
MinNum = MaxNum = 0;
break;
}
}
}

printf("%d %d %d", MaxSum, MinNum, MaxNum);

return 0;
}