#include <bits/stdc++.h>

#define ll long long

using namespace std;

struct Node {
    ll val, pos;
};
Node MAX;
Node MaxNode(Node a, Node b){
    if(a.val > b.val)
        return a;
    else if(a.val < b.val){
        return b;
    }
    if(a.pos < b.pos)
        return a;
    return b;
}
struct segment_tree {
    ll len = 1;
    vector < Node > tree;
    void init(ll x){
        while(len < x){
            len *= 2;
        }
        tree.resize(2 * len - 1, MAX);
    }
    void changeFunc(ll l, ll r, ll cur, ll pos, ll v){
        if(r - l == 1){
            tree[cur].val = v;
            tree[cur].pos = pos;
            return;
        }
        ll m = (r + l) / 2;
        if(pos < m)
            changeFunc(l, m, 2 * cur + 1, pos, v);
        else
            changeFunc(m, r, 2 * cur + 2, pos, v);
        tree[cur] = MaxNode(tree[2 * cur + 1], tree[2 * cur + 2]);
    }
    void change(ll pos, ll v){
        changeFunc(0, len, 0, pos, v);
    }
    Node maxFunc(ll lx, ll rx, ll l, ll r, ll cur){
        if(lx >= l && rx <= r){
            return tree[cur];
        }
        if(lx >= r || rx <= l)
            return MAX;
        ll m = (rx + lx) / 2;
        Node min1 = maxFunc(lx, m, l, r, 2 * cur + 1);
        Node min2 = maxFunc(m, rx, l, r, 2 * cur + 2);
        return MaxNode(min1, min2);
    }
    ll Max(ll l, ll r){
        return maxFunc(0, len, l - 1, r, 0).pos;
    }
};

int main() {
  //  ios_base::sync_with_stdio(false);cin.tie(0);
    MAX.pos = INT_MAX;
    MAX.val = 0;
    ll n;
    cin >> n;
    segment_tree sg;
    sg.init(n);
    vector < ll > v(n);
    for(int i = 0; i < n; i++){
        ll x;
        cin >> x;
        v[i] = x;
        sg.change(i, x);
    }
    vector < ll > p(n + 1);
    for(int i = 1;i <= n;i++){
        ll x;
        cin >> x;
        p[i] += p[i - 1] + x;
    }
    ll s = 0 , l = 1 , r = n;
    while(r - l >= 1){
        ll pos = sg.Max(l , r) + 1;
        s += p[pos] - p[pos - 1];
        ll left = p[pos] - p[l], right = p[r] - p[pos];
        if(left > right){
            l = pos + 1;
        }
        else{
            r = pos - 1;
        }
    }
    cout << s + p[r] - p[r - 1]  << endl;
}


