#include <bits/stdc++.h>
#define file(s) if (fopen(s".in", "r")) freopen(s".in", "r", stdin), freopen(s".out", "w", stdout)
#define Youarestupid ios_base::sync_with_stdio(0);cin.tie(0);
#define all(x) x.begin() , x.end()
#define	pofik continue
#define int long long
#define pb push_back
#define ins insert
#define sz size()
#define F first
#define S second
const int N = 2e5 + 77 , inf = 1e18 + 77 , MOD = 1e9 + 7;
const long double eps = 1e-11;
using namespace std;
int T = 1 , sum;
int binpow(int a , int b){
    if (!b) return 1;
    if (b % 2){
        return (a * binpow(a , b - 1)) % MOD;
    }
    else{
        int val = binpow(a , b / 2);
        return (val * val) % MOD;
    }
}

int n , h[N] , c[N];

struct node{
	int mx , cos , ind;
};

node t[N * 4];

node merge(node a , node b){
	node res = a;
	if(res.mx < b.mx){
		res = b;
	}
	return res;
}

void build(int v , int l , int r){
	if(l == r){
		t[v].mx = h[l];
		t[v].cos = c[l];
		t[v].ind = l;
		return;
	}
	int mid = (l + r) / 2;
	build(v * 2 , l , mid) , build(v * 2 + 1 , mid + 1 , r);
	t[v] = merge(t[v * 2] , t[v * 2 + 1]);
}

node get(int v , int l , int r , int ql , int qr){
	if(ql > r || qr < l) return {-inf , - inf , -inf};
	if(ql <= l && r <= qr) return t[v];
	int mid = (l + r) / 2;
	return merge(get(v * 2 , l , mid , ql , qr) , get(v * 2 + 1 , mid + 1 , r , ql , qr));
}

void solve(){
	cin >> n;
	for(int i = 1; i <= n; i++) cin >> h[i];
	for(int i = 1; i <= n; i++) cin >> c[i];
	build(1 , 1 , n);
	set < pair < int , int > > st;
	st.ins({1 , n});
	int ans = 0;
	while(st.sz){
		auto t = *st.begin();
		st.erase(t);
		int l = t.F;
		int r = t.S;
		if(l == r){
			ans += c[r];
			pofik;
		}
		node x = get(1 , 1 , n , l , r);
		node x1 = get(1 , 1 , n , x.ind + 1 , r);
		node x2 = get(1 , 1 , n , l , x.ind - 1);
		if(x1.cos > x2.cos){
			st.ins({l , x.ind - 1});
			ans += x.cos;
		}
		else{
			st.ins({x.ind + 1 , r});
			ans += x.cos;
		}
	}
	cout << ans;
}

signed main(){
    Youarestupid
//	cin >> T;
    while(T--){
    	solve();
    }
}
/*
  ___      __                      _
 |   \    | |          _____      | |  _
 | |\ \   | |  __  __ |  __ \     | | (_)
 | | \ \  | | | |  | || |  \_\__ _| |  _
 | |  \ \ | | | |  | || |    / _` | | | |
 | |   \ \| | | |__| || |   / (_| | | | |
 |_|    \___| |______||_|    \_,__|_| |_|

*/







