Source Code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define ss second
#define ff first
#define pb push_back
#define mp make_pair

const int N=300050;
ll n;
ll a[N],b[N];
int main(){
    ios_base::sync_with_stdio(0);
    cin>>n;
    ll SA=0,SB=0;
    for(int i=0;i<n;i++){
        cin>>a[i];
        SA+=a[i];
    }
    for(int i=0;i<n;i++){
        cin>>b[i];
        SB+=b[i];
    }
    if(SA>SB){
        cout<<-1<<endl;
        return 0;
    }
    ll tmp=0;
    ll frst=n;
    ll travel=0;
    ll ans=SA+n-1+n-1;
    for(ll i=0;i<n;i++){
        tmp+=(b[i]-a[i]);
        //cout<<tmp<<endl;
        if(tmp<0){
            frst=min(frst,i);
            ans=min(ans,SA+n-1+travel+n-1-i);
        }
        if(tmp>=0&&frst!=n){
            travel+=2*(i-frst);
            if(i==n)travel-=(i-frst);
            frst=n;
        }
    }
    //cout<<ans<<' '<<travel<<endl;
    ans=min(ans,SA+travel+n-1);
    cout<<ans<<endl;
    return 0;
}
Copy
Shooting Balloons IDK
GNU G++17
0 ms
636 KB
Wrong Answer