Example 7 Given that $x_{1}, x_{2}, \cdots, x_{40}$ are all positive integers, and $x_{1}+x_{2}+\cdots+x_{40}=58$. If the maximum value of $x_{1}^{2}+x_{2}^{2}+\cdots+x_{40}^{2}$ is $A$, and the minimum value is $B$, then $A+B=$ $\qquad$
Solution: Since there are only a finite number of ways to write 58 as the sum of 40 positive integers, the maximum and minimum values of $x_{1}^{2}+x_{2}^{2}+\cdots+x_{40}^{2}$ exist.
Assume without loss of generality that $x_{1} \leqslant x_{2} \leqslant \cdots \leqslant x_{40}$.
If $x_{1}>1$, then
$$
x_{1}+x_{2}=\left(x_{1}-1\right)+\left(x_{2}+1\right) \text {, }
$$

and
$$
\begin{array}{l}
\left(x_{1}-1\right)^{2}+\left(x_{2}+1\right)^{2} \\
=x_{1}^{2}+x_{2}^{2}+2\left(x_{2}-x_{1}\right)+2 \\
>x_{1}^{2}+x_{2}^{2} .
\end{array}
$$

Thus, when $x_{1}>1$, $x_{1}$ can be gradually adjusted to 1, at which point the value of $x_{1}^{2}+x_{2}^{2}+\cdots+x_{40}^{2}$ will increase.

Similarly, $x_{2}, x_{3}, \cdots, x_{39}$ can be gradually adjusted to 1, at which point the value of $x_{1}^{2}+x_{2}^{2}+\cdots+x_{40}^{2}$ will increase.

Therefore, when $x_{1}, x_{2}, \cdots, x_{39}$ are all 1 and $x_{40}=19$, $x_{1}^{2}+x_{2}^{2}+\cdots+x_{40}^{2}$ reaches its maximum value, i.e.,
$$
A=\underbrace{1^{2}+1^{2}+\cdots+1^{2}}_{39 \uparrow}+19^{2}=400 \text {. }
$$

If there exist two numbers $x_{i}$ and $x_{j}$ such that
$$
\begin{array}{l}
\quad x_{j}-x_{i} \geqslant 2(1 \leqslant i<j \leqslant 40), \\
\quad \text { then }\left(x_{i}+1\right)^{2}+\left(x_{j}-1\right)^{2} \\
\quad=x_{i}^{2}+x_{j}^{2}-2\left(x_{j}-x_{i}-1\right) \\
<x_{i}^{2}+x_{j}^{2} .
\end{array}
$$

This indicates that, in $x_{1}, x_{2}, \cdots, x_{40}$, if the difference between any two numbers is greater than 1, then by increasing the smaller number by 1 and decreasing the larger number by 1, the value of $x_{1}^{2}+x_{2}^{2}+\cdots+x_{40}^{2}$ will decrease.

Therefore, when $x_{1}^{2}+x_{2}^{2}+\cdots+x_{40}^{2}$ reaches its minimum value, the difference between any two numbers in $x_{1}, x_{2}, \cdots, x_{40}$ does not exceed 1.

Hence, when $x_{1}=x_{2}=\cdots=x_{22}=1$ and $x_{23}=x_{24}=\cdots=x_{40}=2$, $x_{1}^{2}+x_{2}^{2}+\cdots+x_{40}^{2}$ reaches its minimum value, i.e.,
$$
B=\frac{1^{2}+1^{2}+\cdots+1^{2}}{22 \uparrow}+\frac{2^{2}+2^{2}+\cdots+2^{2}}{18 \uparrow}=94 .
$$

Thus, $A+B=494$.