#pragma GCC optimize("O3")
#include <bits/stdc++.h>
#define int long long
#define ll long long
#define f first
#define s second
#define pb push_back
#define sz(x) (int) x.size()
#define all(x) begin(x), end(x)
using namespace std;
 
const int N = 2e5 + 1, inf = LLONG_MAX / 2ll ;
 
struct SegmentTree {
    struct Node {
        ll mn = LLONG_MAX;
        void combine(Node a, Node b) {
            mn = min(a.mn, b.mn);
        }
    };
    vector<Node> nodes;
    int size;
 
    SegmentTree(int n) {
        size = 1 << __lg(n * 2 - 1);
        nodes.assign(size * 2 - 1, Node());
    }
 
    void modify(ll v, int i, int x, int lx, int rx) {
        if(rx - lx == 1) {
            nodes[x].mn = v;
            return;
        }
        int mx = (lx + rx) / 2;
        if(i < mx) modify(v, i, x * 2 + 1, lx, mx);
        else modify(v, i, x * 2 + 2, mx, rx);
        nodes[x].combine(nodes[x * 2 + 1], nodes[x * 2 + 2]);
    }
 
    void modify(ll v, int i) {
        modify(v, i, 0, 0, size);
    }
 
    Node get(int l, int r, int x, int lx, int rx) {
        if(lx >= r || l >= rx) return Node();
        if(lx >= l && rx <= r) return nodes[x];
        int mx = (lx + rx) / 2;
        Node lft = get(l, r, x * 2 + 1, lx, mx);
        Node rgt = get(l, r, x * 2 + 2, mx, rx);
        Node res; res.combine(lft, rgt);
        return res;
    }
 
    Node get(int l, int r) {
        return get(l, r, 0, 0, size);
    }
};
 
void solve() {
    int n; cin >> n;
    vector<ll> h(n + 1);
    for(int i = 1; i <= n; i++) {
        cin >> h[i];
    }
    vector<ll> c(n + 2);
    for(int i = 1; i <= n; i++) {
        cin >> c[i];
    }
    vector<ll> dp(n + 1, LLONG_MAX);
    dp[0] = 0;
    SegmentTree st(n + 1);
    st.modify(0, 0);
    vector<int> left;
    left.push_back(0);
    vector<pair<ll, ll> > right;
    right.push_back({1, c[1]});
    for(int i = 1; i <= n; i++) {
        dp[i] = dp[i - 1] + c[i];
        while(left.size() > 1 && h[left.back()] < h[i]) {
            left.pop_back();
        }
        dp[i] = c[i] + st.get(left.back(), i).mn;
        left.push_back(i);
        while(right.size() && h[right.back().first] <= h[i]) {
            right.pop_back();
        }
        if(right.size()) {
            dp[i] = min(dp[i], right.back().second);
            right.push_back(make_pair(i + 1, min(dp[i] + c[i + 1], right.back().second)));
        } else {
            right.push_back({i + 1, dp[i] + c[i + 1]});
        }
        st.modify(dp[i], i);
    }
    cout << dp.back();
    return;
}
 
signed main() {
    ios_base::sync_with_stdio(NULL);
    cin.tie(0);cout.tie(0);
    int T = 1 ;
    while (T--) {
        solve ( ) ;
    }
    return 0 ;
}