After the join, the new sum is
\begin{align*}
&(40)(40) + mn\\[6pt]
=\; &1600 + mn\\[6pt]
=\; &1600 + m(50-m)
\end{align*}
and the new average is
$$f(m) = \frac{1600 + m(50-m)}{40 + m}$$
We want to maximize $f(m)$, for positive integer values of $m$. Taking the derivative, we get
$$f^{\prime}(m) = \frac{-m^2 - 80m + 400}{\left(m + 40\right)^2}$$
which has two real roots, but only one positive real root, $\,r = -40 + 20\sqrt{5} \approx 4.72$.
From the algebraic form of $f^{\prime}(m)$, it follows that
- $0 < m < r \implies f^{\prime}(m) > 0$
- $m > r \implies f^{\prime}(m) < 0$
Since $m$ is required to be a positive integer, and $4 < r < 5$, it follows that the optimal $m$ must be either $4$ or $5$.
Comparing $f(4)$ and $f(5)$, we find
$$f(4) = \frac{446}{11} < f(5) = \frac{365}{9}$$
It follows that the maximum possible new average is
$$f(5) = \frac{365}{9} = 40 + \frac{5}{9} \approx 40.56$$