import Data.List
import Data.Tree
import Data.Array  --変数衝突
import Data.Array.Unboxed
import Data.Array.MArray
import Data.Array.ST
import qualified Data.Vector.Unboxed as V (last,(!),fromList,Vector)
import Control.Monad
import Control.Monad.ST

type Bs = V.Vector Int
type DP s = STUArray s Int Int

{-
セグ木について
配列dp[1]~[2*n]
添え字iに対して、親ノードはi`div`2、子ノードは2*i,2*i+1
高さは (floor logBase 2 (fromIntegral i))+1
範囲は、(,)
-}

--範囲が１の部分を読み込む
read1SegT :: DP s -> Int -> Int -> ST s Int
read1SegT dparr n i = readArray dparr (i-1+2^(floor $ log $ (fromIntegral n :: Double)))

--logN
readmaxSegT :: DP s -> (Int,Int) -> Int -> Int -> Int -> ST s Int
readmaxSegT dparr (l,r) n i max0
  | 2*n-1 < i   = return max0 ---Error??-----
  | otherwise = do
    let mid = (l+r)`div`2
    a <- readArray dparr i
    if mid < n
      then readmaxSegT dparr (mid+1,r) n (2*i+1) (max a max0)
      else readmaxSegT dparr (l,mid) n (2*i)   (max a max0)

--セグ木の更新,O(c*logN)
modifyRSegT :: DP s -> (Int,Int) -> (Int,Int) -> Int -> Int -> Int -> ST s ()
modifyRSegT dparr (defl,defr) (l,r) a n i
  | defr < defl = return ()
  | 2*n-1 < i   = error "modifyRSegT Error" ---Error??
  | defl == l && defr >= r = do
   a' <- readArray dparr i
   if a <= a' then return () else writeArray dparr i a
   modifyRSegT dparr (r+1,defr) (1,n) a n 1
  | otherwise  = do
   let mid = (l+r)`div`2
   if mid < defl then modifyRSegT dparr (defl,defr) (mid+1,r) a n (2*i+1)
     else modifyRSegT dparr (defl,defr) (l,mid) a n (2*i)

dp_i :: DP s -> Int -> [Int] -> [Int] -> ST s ()
dp_i dparr n [] [] = return ()
dp_i dparr n (h:hs) (a:as) = do
  nowa <- readmaxSegT dparr (1,n) h 1 0
  modifyRSegT dparr (h,n) (1,n) (nowa+a) n 1
  dp_i dparr n hs as

solve :: Int -> [Int] -> [Int] -> ST s Int
solve n hs as = do
  dparr <- newArray (1,2*n-1) 0 -- n+n/2+n/4+...<=2*n-1
  dp_i dparr n hs as
  readmaxSegT dparr (1,n) n 1 0

main :: IO ()
main = do
 n  <- read <$> getLine
 hs <- map read.words <$> getLine
 as <- map read.words <$> getLine
 putStrLn $ show $ runST $ solve n hs as

mod0 :: Int -> Int
mod0 n = if n < 1000000007 then n else mod n 1000000007
