A sequence of positive integers $a_{n}$ begins with $a_{1}=a$ and $a_{2}=b$ for positive integers $a$ and $b$. Subsequent terms in the sequence satisfy the following two rules for all positive integers $n$ :
$$
a_{2 n+1}=a_{2 n} a_{2 n-1}, \quad a_{2 n+2}=a_{2 n+1}+4 .
$$

Exactly $m$ of the numbers $a_{1}, a_{2}, a_{3}, \ldots, a_{2022}$ are square numbers. What is the maximum possible value of $m$ ? Note that $m$ depends on a and $b$, so the maximum is over all possible choices of $a$ and $b$.
Solution
We begin by observing that no two positive square numbers differ by four. This can be seen by considering $a^{2}-b^{2}=(a-b)(a+b)$ which is at least 8 if it is even, or by noting that the gaps between the positive squares are the odd numbers starting with 3 , no two of which sum to 4 .

For $n \geq 1$ we have that $a_{2 n+1}$ and $a_{2 n+2}$ differ by 4 , so at most one of them is a square.
For $n \geq 2$ we have that $a_{2 n+2}=a_{2 n} a_{2 n-1}+4$ which is $\left(a_{2 n-1}+2\right)^{2}$ and so always a square.
Thus $a_{6}, a_{8}, \ldots a_{2022}$ are all square and $a_{5}, a_{7}, \ldots a_{2021}$ are not, giving 1009 squares from $a_{5}$ to $a_{2022}$.

The sequence begins $a, b, a b, a b+4$. The last two differ by 4 so are not both square which implies that at most three of the first four terms are squares. Moreover, if $a$ and $b$ are both square numbers, then $a b$ will also be a square.

Thus there are at most 1012 squares among the first 2022 terms of the sequence. This is attained if (and only if) $a$ and $b$ are both squares.