Let $A = \{1, 2,\dots, 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,\dots,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.