#include<bits/stdc++.h>
#define int int64_t

#define pii pair<int,long double>
#define fi first
#define se second

using namespace std;
typedef long double ld;
const int N = 2e5 + 10;

int st[N][23];
int c[N];
int lg[N];
unordered_map<int,int>pos;

int get(int l,int r){
    int i = lg[r - l + 1];
    return max(st[l][i],st[r - (1ll << i) + 1][i]);
}

int v (int l, int r) {
//    cerr << "! " << l << ' ' << r << ' ' << get(l,r) << ' ' << pos[get(l,r)] << '\n';
    if(l > r)return 0;
    if (l == r) return c[l];
    int p = pos[get(l, r)];
    if (p == l or p == r) return c[p];
    int a1 = v(l, p - 1);
    int a2 = v(p + 1, r);
    if (a1 > a2) return c[p] + a2;
    return c[p] + a1;
}
mt19937 gen(time(0));

void solve(){
    int n = 200000;
    cin >> n;
    vector<int>a(n + 20);
    for(int i =1  ;i <= n; ++ i){
        cin >> a[i];
//        a[i] = i + 1000000000;
    }
//    shuffle(a.begin(),a.end(),gen);

    for(int i =1; i <= n; ++ i){
        cin >> c[i];
//        c[i] = gen() % 1000000;
        pos[a[i]] = i;
        st[i][0] = a[i];
    }
    for(int k = 1; k < 23; ++ k){
        for(int i = 1; i + (1ll << (k - 1)) <= n; ++ i){
            st[i][k] = max(st[i][k - 1],st[i + (1ll << (k - 1))][k - 1]);
        }
    }
    vector<int>pref(n + 2);
    pref[0] = c[0];
    for(int i = 1; i <= n; ++ i){
        pref[i] =pref[i - 1] + c[i];
    }
    auto get_sum = [&](int l,int r){
        if(l == 0)return pref[r];
        else return pref[r] - pref[l-  1];
    };
    vector<int>dp(n + 1);
    cout << v(1,n) << '\n';
 }


int32_t main(){
    #ifdef LOCAL
        freopen("input.txt","r",stdin);
        freopen("output.txt","w",stdout);
    #endif // LOCAL
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    lg[1] = 0;
    for(int i = 2; i < N; ++ i){
        lg[i] = lg[i / 2] + 1;
    }
    int Q = 1;
//    cin >> Q;
    while(Q -- )solve();
    return 0;
}
