Under construction

Still being built. Things may change

Zigzag

Time limit2sMemory limit256 MB

Summary
Find the longest sequence that is a subsequence of both given arrays and whose consecutive triples strictly alternate up and down.
Level

Medium6 of 10

Topics
Dynamic programming, Array
Solved
No attempts yet

Problem

A sequence of numbers x(1),x(2),…,x(k)x(1), x(2), \ldots, x(k) is zigzag if no three of its consecutive elements form a nonincreasing or nondecreasing sequence. More precisely, for all i=1,2,…,k−2i = 1, 2, \ldots, k-2, either x(i+1)<x(i)x(i+1) < x(i) and x(i+1)<x(i+2)x(i+1) < x(i+2), or x(i+1)>x(i)x(i+1) > x(i) and x(i+1)>x(i+2)x(i+1) > x(i+2).

You are given two sequences a(1),…,a(n)a(1), \ldots, a(n) and b(1),…,b(m)b(1), \ldots, b(m). Remove elements from both sequences so that they become equal and the remaining sequence is zigzag. If the minimum number of removed elements is kk, the answer is m+n−km+n-k. Find the length of the longest common zigzag subsequence.

Input

The first line contains nn (1≤n≤20001\leq n \leq 2000), followed by nn integers a(1),…,a(n)a(1), \ldots, a(n). The second line contains mm (1≤m≤20001 \leq m \leq 2000), followed by mm integers b(1),…,b(m)b(1), \ldots, b(m). Every a(i)a(i) and b(i)b(i) is in the range [−109,109][-10^9, 10^9].

Output

Print one line containing the length of the longest common zigzag subsequence of aa and bb.

Examples1

  1. Example 1

    Input
    5 1 2 5 4 3
    5 4 1 2 5 3
    
    Expected output
    3