#include<bits/stdc++.h>
#define ll long long
using namespace std;
class SegmentTree {
public:
int n;
vector<ll> tree;
SegmentTree(int n) : tree(2 * n + 10), n(n){};
void upd(int pos, ll value) {
for (tree[pos += n] = value; pos > 1; pos >>= 1)
tree[pos >> 1] = max(tree[pos], tree[pos ^ 1]); // Range sum
}
long long query(int l, int r) {
long long res = 0;
for (l += n, r += n + 1; l < r; l >>= 1, r >>= 1) {
if (l & 1) res = max(res, tree[l++]);
if (r & 1) res = max(res, tree[--r]);
}
return res;
}
};
int main(){
int t;
cin >> t;
while (t--){
ll n, MX = 0, ans = 0;
cin >> n;
ans = n;
vector<ll> a(n + 1), b(n + 1), c(n + 1), d(i);
for (int i = 1; i <= n; i++){
cin >> a[i];
}
for (int i = 1; i <= n; i++){
cin >> b[i];
}
SegmentTree st(n + 1);
for (int i = n; i > 0; i--){
c[a[i]] = max(c[a[i]], b[i]);
ll mx = st.query(a[i] + 1, n + 1);
ll cur = max(c[a[i]] + mx, st.query(a[i], a[i]));
st.upd(a[i], cur);
d[i] = cur;
}
for (int i = 1; i <= n; i++){
if (d[i] >= MX){
MX = d[i];
ans = n - (i - 1);
}
}
cout << ans << endl;
}
}