原题地址
https://pintia.cn/problem-sets/1268384564738605056/problems/1268385944106778625
解题思路
我还是用的在线处理的方式,然后判断是否要更新当前的fst和lst值。
注意事项
1. 考虑只有负数和0的情况。我对这个的处理就比较粗糙了,直接用hasN和has0特判是否存在负数和0,然后直接输出结果(如果全是负数和0的话输出一定是0 0 0)。
参考代码
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
typedef double db;
typedef long long LL;
typedef vector<int> VI;
const int inf = 2e9;
const LL INF = 8e18;
const int maxn = 5e5 + 5;
int main() {
int ans = 0, tmp = 0, k, num, fst, lst, fnow, lnow;
bool flag = false, hasP = false, has0 = false;
cin >> k;
for (int i = 0; i < k; i++) {
cin >> num;
if (num > 0) hasP = true;
if (num == 0) {
has0 = true;
}
if (i == 0) {
fnow = fst = num;
}
if (flag) {
fnow = num;
flag = false;
}
lnow = num;
if (tmp + num >= 0) {
tmp += num;
fst = (tmp > ans) ? fnow : fst;
lst = (tmp > ans) ? num : lst;
ans = max(ans, tmp);
}
else {
tmp = 0;
flag = true;
}
}
if (!hasP) {
if (has0) printf("0 0 0");
else printf("0 %d %d", fst, lnow);
}
else printf("%d %d %d", ans, fst, lst);
return 0;
}