Maximum number of crossed matchings between two sequences
Back to OJ problems …
Problem
Given two sequences of integers,and
, we are allowed to match an integer
from the first sequence with an integer
from the second sequence only if
. No integer in either sequence can be matched with more than one integer in the other sequence.
Each matching must cross with another one and only one different matching. Two matchingsand
are considered crossed iff
and
, or if
and
. The two matchings are considered different iff
.
We are required to know the maximum number of crossed matchings that can be done. For example, in the following figure, the maximum is 4.

Solution
The key to solve this problem is to notice its similarity to the well-known longest common subsequence (LCS) problem. However, while the LCS problem asks for the maximum number of uncrossed matchings, this problem asks for the maximum number of crossed matchings.
Letbe a sequence that contains the first
elements of
in order. Similarly,
is a sequence that contains the first
elements of
in order. Let
be the maximum number of crossed matchings between the two sequences
and
. We define the the predicate
to be true if and only if there is a crossed matching between
and
that involves the last element of
and the last element of
; that is,
The importance of this predicate is that it determines whether adding/dropping the last element inor
will add/drop a crossed matching. If the predicate
is satisfied, then we are interested to know what elements are involved in this boundary crossed matching. Let
denote the index of the last occurrence of
in
; that is,
. Similarly,
is the index of the last occurrence of
in
. If we are going to count this boundary crossed matching in our maximal set of crossed matchings, then we will have to uncount any other crossed matchings that involve elements between
and
inclusive, or elements between
and
inclusive. This effectively means going back to
. Therefore we shouldn’t count a boundary crossed matching unless there are no other crossed matchings that will be uncoutned for this purpose. We define
recursively as follow:
Function
If
or
Then Return
If
Then
Return
which is quite similar to the recursive solution of the LCS problem. The problem can then be solved efficiently using dynamic programming.