题解 | #最大连续子序列#
最大连续子序列
https://www.nowcoder.com/practice/afe7c043f0644f60af98a0fba61af8e7
#include <iostream> using namespace std; long long a[10001]; long long dp[10001]; long long maxinum = -INT32_MAX; int count = 0; void maxseq(int n) { for (int i = 0; i < n; i++) { if (i == 0) { dp[i] = a[i]; } else { dp[i] = max(a[i], a[i] + dp[i - 1]); } if (dp[i] > maxinum) { maxinum = dp[i]; count = i; } } } int main() { int n; bool flag = false; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%lld", &a[i]); if (a[i] >= 0) { flag = true; } } maxseq(n); if (flag) { printf("%lld", maxinum); int end = count; while (maxinum != 0) { maxinum = maxinum - a[count]; if (maxinum == 0) { break; } count--; } int first = count; printf(" %d", a[first]); printf(" %d", a[end]); } else { //都小于0 printf("0 %d %d", a[0], a[n - 1]); } return 0; }