1007 Maximum Subsequence Sum

题目大意:
输出最大子序列和,以及首尾元素。

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
#include <bits/stdc++.h>
using namespace std;

int main() {
int len;
scanf("%d", &len);
int num[len + 1];
int left = 0, right = len - 1, temp = 0, tempIndex = 0, sum = -1;
for (int i = 0; i < len; i++) {
scanf("%d", &num[i]);
temp += num[i];
if (temp < 0) {
temp = 0;
tempIndex = i + 1;
} else if (temp > sum) {
sum = temp;
left = tempIndex;
right = i;
}
}
if (sum < 0) sum = 0;
printf("%d %d %d\n", sum, num[left], num[right]);

return 0;
}

10
-10 1 2 3 4 -5 -23 3 7 -21

10 1 4

由于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). 上面的temp要大于sum才更新。