import sys
def solve():
"""
Solves a single test case for the maximum score, minimum size problem.
"""
n = int(sys.stdin.readline())
a = list(map(int, sys.stdin.readline().split()))
b = list(map(int, sys.stdin.readline().split()))
# Fenwick Tree for Range Maximum Queries
class MaxBIT:
def __init__(self, size):
self.tree = [0] * (size + 1)
def update(self, idx, val):
while idx < len(self.tree):
self.tree[idx] = max(self.tree[idx], val)
idx += idx & -idx
def query(self, idx):
max_val = 0
while idx > 0:
max_val = max(max_val, self.tree[idx])
idx -= idx & -idx
return max_val
# 1. Forward pass to find the global maximum score (s_max)
ft1 = MaxBIT(n)
s_max = 0
for i in range(n):
# Find max score of subsequences ending with a value less than a[i]
max_prev_score = ft1.query(a[i] - 1)
current_score = max_prev_score + b[i]
ft1.update(a[i], current_score)
s_max = max(s_max, current_score)
# 2. Backward pass to find the max score for all subsequences starting at i
suffix_scores = [0] * n
ft2 = MaxBIT(n)
for i in range(n - 1, -1, -1):
# Query for values > a[i] using coordinate transformation
# Values > k are mapped to transformed indices < n - k + 1
max_next_score = ft2.query(n - a[i])
current_score = max_next_score + b[i]
suffix_scores[i] = current_score
# Update using the transformed index n - a[i] + 1
ft2.update(n - a[i] + 1, current_score)
# 3. Find the latest starting index `k` that can achieve s_max
max_score_in_suffix = 0
for k in range(n - 1, -1, -1):
max_score_in_suffix = max(max_score_in_suffix, suffix_scores[k])
if max_score_in_suffix == s_max:
# This is the latest start point, so it gives the minimum size
print(n - k)
return
def main():
"""
Main function to handle multiple test cases.
"""
try:
t = int(sys.stdin.readline())
for _ in range(t):
solve()
except (IOError, ValueError):
# Handles potential empty lines or formatting errors at the end of input
pass
if __name__ == "__main__":
main()