Source Code
#include <bits/stdc++.h>
using namespace std;
#define ll long long
ll v[1000000];
int main(){
    ios_base::sync_with_stdio(0);
    int n;
    cin>>n;
    ll sumBalloons = 0;
    ll sumBullets = 0;
    for (int i=1;i<=n;i++) {
        ll x;
        cin>>x;
        v[i] = -x;
        sumBalloons += x;
    }
    for (int i=1;i<=n;i++) {
        ll x;
        cin>>x;
        v[i] += x;
        sumBullets += x;
    }
    if (sumBalloons > sumBullets) {
        cout<<-1<<endl;
        return 0;
    }
    ll baseCost = n-1 + sumBalloons;
    ll ret = baseCost + n-1;
    ll curCost = baseCost;
    int first = -1;
    ll sum = 0;
    for (int i=1;i<=n;i++) {
        sum += v[i];
        if (first!=-1 && sum>=0) {
            ret = min(ret, curCost + n - first);
            curCost += 2*(i-first);
        } else if (first == -1 && sum<0) {
            first = i;
        }
    }
    cout<<min(ret, curCost)<<endl;
}

Copy
Shooting Balloons RedNextCentury
GNU G++17
50 ms
3.0 MB
Wrong Answer