Solution #
First, let’s define the function , i.e. the sum of consecutive months starting at .
Now, let’s prove that if is one answer and , then is also an answer: . Thus we can always find an answer greater than .
Then, consider the case where . If is an answer, since , is also an answer. Thus it’s sufficient to check if is the answer.
Lastly, when , we need the help of the prefix sum. Define and . We want to find a such that for each , we have:
Since , the numbers after the window must be , so the formula can be rewrite as:
For each , the corresponding is , this means if the max value of the LHS is smaller than , then is a answer.
Code #
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); ++i)
#define all(x) (x).begin(), (x).end()
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<ll> a(n);
forn(i, (n + 1) / 2) {
cin >> a[i];
}
int x;
cin >> x;
for (int i = (n + 1) / 2; i < n; i++) a[i] = x;
vector<ll> ps(n + 1);
partial_sum(all(a), ps.begin() + 1);
if (ps.back() > 0) return cout << n, 0;
if (x >= 0) return cout << -1, 0;
ll N2 = n / 2, N1 = n - N2, sum = ps.back();
ll mx = -1e18;
for (int i = 0; i <= N1; i++) {
mx = max(mx, ps[i] + x * ll(n - i));
if (mx < sum + x * ll(n - i)) {
cout << n - i;
return 0;
}
}
cout << -1;
return 0;
}