How to choose two random variables taking values in a finite space, with given distributions, such that probability that they are equal is maximized? Let A = {1, 2, ..., n}, and let X and Y be two random variables on the same space, taking values in A, and distributions given by:
P(X = i) = $p_i$, and P(Y = i) = $q_i$, for any i in {1,2,...,n}
What is the maximum possible value of P(X = Y)?
Basically, we have to choose a good joint distribution of X and Y, such that the sum of diagonal entries in the joint distribution table/matrix is maximized. For n = 2, this is easy to do, and I get the answer (1 - |$p_1$ - $q_1$|). But even for n = 3, I am not able to do much. A  solution/strategy for general n would be appreciated.

First for any $n$ we must have $P(X=Y=n)\leq p_i\wedge q_i$.
Set $$\pi = \sum_{i=1}^n p_i\wedge q_i.$$
We aim to choose a distribution such that $P(X=Y)=\pi$.
To do this set $$\begin{align}p'_i &= p_i - (p_i\wedge q_i) \\ q'_i &= q_i - (p_i\wedge q_i)\end{align}$$ 
Then
$\sum_{i=1}^n p'_i = \sum_{i=1}^nq'_i=1-\pi$.
So proceed as follows.
$\circ\qquad$With probability $\pi$ assign $X=Y$ according to the distribution $\dfrac{p_i\wedge q_i}{\pi}$.
$\circ\qquad$With probability $1-\pi$ assign $X$ and $Y$ independently.
So set 
$$P(X=i,Y=j)=\begin{cases}p_i\wedge q_i &:\mathop{if}\,i=j, \\
\frac{p'_i\cdot q'_j}{1-\pi} &:\mathop{if}\,i\neq j. 
\end{cases}$$
Then summing over $j$ we have 
$$\begin{align}P(X=i) &= (p_i\wedge q_i) + \sum_{j=1}^n \frac{p'_i\cdot q'_j}{1-\pi} \\
&= (p_i\wedge q_i) + p'_i\sum_{j=1}^n \frac{ q'_j}{1-\pi} \\
&=p_i.\end{align}$$
