#include <bits/stdc++.h>
using namespace std;
#define modulo ll (1e9 + 7)
#define neig(a, u, e, v) for(int v, e = (a).head[u] ; ~e and (v = (a).to[e], 1) ; e = (a).nxt[e])
typedef long long ll;
const int N = 2e5 + 9, M = 1e6 + 9, OO = 0x3f3f3f3f;
const ll llOO = 0x3f3f3f3f3f3f3f3f;
int main() {
cin.tie(0);
cin.sync_with_stdio(0);
ll n; cin >> n;
ll ballons[n], bullets[n];
for(int i = 0;i < n;i++)
cin >> ballons[i];
for(int i = 0;i < n;i++)
cin >> bullets[i];
if(accumulate(bullets, bullets + n, 0ll) < accumulate(ballons, ballons + n, 0ll)){
return puts("-1");
}
ll rem = 0, smallestIdx = -1, totalBullets = 0, ans = 0;
for(int i = 0;i < n;i++){
if(i < n - 1) ans++;
totalBullets += bullets[i];
ll mn = min(totalBullets, ballons[i]);
totalBullets -= mn;
ballons[i] -= mn;
ans += mn;
if(ballons[i]){
if(smallestIdx == -1){
smallestIdx = i;
}
rem += ballons[i];
continue;
}
if(rem && totalBullets >= rem){
ans += (i - smallestIdx) * (i < n - 1 ? 2 : 1);
ans += rem;
totalBullets -= rem;
smallestIdx = -1;
rem = 0;
}
}
cout << ans;
}
Copy