题意:
找到和最大的子数组,输出这个最大和,且输出下标最小的一对数,代表以这对数为端点的子数组的和为这个最大和。
有个坑点是如果所有数都是负数,需要输出0 a[1] a[n]
分析:
可以发现如果当前的前缀和已经小于0,那么如果我选择这段前缀一定会对我之后的答案有负贡献,那我不如不要这一段前缀,重新选择之后的一个非负数作为子数组的起点,然后继续往后延展。
#include<bits/stdc++.h>
#define endl '\n'
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
const int N = 5e5 + 10;
const ll INF = 1e15;
const int mod = 1e9 + 7;
int n;
int a[N];
ll sum, ans;
int pos, poe, res;
void solve() {
sum = 0, res = 1;
for(int i = 1; i <= n; ++ i) {
if(sum < 0) sum = a[i], res = i; //更新起点
else sum += a[i];
if(ans < sum) { //更新答案
ans = sum;
poe = i;
pos = res;
}
}
}
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int f = 0;
cin >> n;
for(int i = 1; i <= n; ++ i) {
cin >> a[i];
if(a[i] >= 0) f = 1;
}
if(!f) {
cout << 0 << " " << a[1] << " " << a[n] << endl;
return 0;
}
solve();
cout << ans << " " << a[pos] << " " << a[poe] << endl;
return 0;
}
/*
*/