Suppose we have a source interval $(x_1, x_2)$ and a target interval $(y_1, y_2)$. We want to find an integer $k\in\mathbb{Z}$ such that the new offset interval $(x_1-Nk, x_2-Nk)$ (for some $N\in\mathbb{R}$) maximizes the size of the intersection of the new interval and the target interval.
Formally we can write this as $$ \max_k\left( \min\{x_2 - Nk, y_2\} - \max\{x_1-Nk, y_1\} \right) $$
How can one go about solving this? I have found a closed solution when it is guaranteed the source interval can be offset to be entirely contained by the target, but I'm unsure how to generalise that result.
First note that $$ \max_k\left( \min\{x_2 - Nk, y_2\} - \max\{x_1-Nk, y_1\} \right) = \max_k\left( \min\{x_2 - Nk, y_2\} + \min\{-x_1+Nk, -y_1\} \right).$$ You can solve this maximin problem via mixed integer linear programming by introducing two decision variables to represent the $\min$ expressions. Explicitly, the problem is to maximize $u+v$ subject to linear constraints \begin{align} u &\le x_2 - Nk \\ u &\le y_2 \\ v &\le -x_1 + Nk \\ v &\le -y_1 \end{align}