#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 5005;
const int inf = 1e9;
int n;
int a[maxn],b[maxn];
int bit[maxn];
vector<int> g[2*maxn];
int l[maxn],r[maxn];
int L[2*maxn],R[2*maxn];
void upd(int i,int x){
while(i<=n){
bit[i]=max(bit[i],x);
i+=i&-i;
}
}
int get(int i){
int res=0;
while(i){
res=max(res,bit[i]);
i-=i&-i;
}
return res;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
cin>>n;
vector<int> v;
for(int i=1;i<=n;i++){
cin>>a[i];
v.push_back(a[i]);
}
for(int i=1;i<=n;i++){
cin>>b[i];
v.push_back(b[i]);
}
sort(v.begin(),v.end());
v.erase(unique(v.begin(),v.end()),v.end());
for(int i=1;i<=2*n;i++) g[i].clear();
for(int i=1;i<=n;i++){
a[i]=lower_bound(v.begin(),v.end(),a[i])-v.begin()+1;
b[i]=lower_bound(v.begin(),v.end(),b[i])-v.begin()+1;
g[b[i]].push_back(i);
}
stack<int> st;
for(int i=n;i>=1;i--){
while(st.size() && a[st.top()]<=a[i]) st.pop();
if(st.size()) r[i]=st.top();
else r[i]=n+1;
st.push(i);
}
while(st.size()) st.pop();
for(int i=1;i<=n;i++){
while(st.size() && a[st.top()]<=a[i]) st.pop();
if(st.size()) l[i]=st.top();
else l[i]=0;
st.push(i);
}
for(int i=1;i<=n;i++){
int x=a[i];
while(R[x]<(int)g[x].size() && g[x][R[x]]<r[i]) R[x]++;
R[x]--;
while(L[x]<(int)g[x].size() && g[x][L[x]]<=l[i]) L[x]++;
if(L[x]>R[x]) continue;
if(L[x]>=(int)g[x].size()) continue;
if(R[x]>=(int)g[x].size()) continue;
int best=-inf;
for(int j=L[x];j<=R[x];j++){
best=max(best,get(g[x][j]-1)-j);
upd(g[x][j],best+j+1);
}
}
cout<<get(n)<<"\n";
return 0;
}