Example 4.2.4. Given positive real numbers $x_{1}, x_{2}, \ldots, x_{n} \in[a, b]$, find the maximum value of
$$\left(x_{1}-x_{2}\right)^{2}+\left(x_{1}-x_{3}\right)^{2}+\cdots+\left(x_{1}-x_{n}\right)^{2}+\left(x_{2}-x_{3}\right)^{2}+\cdots+\left(x_{n-1}-x_{n}\right)^{2}$$
Solution. Denote the above expression by $F$. Notice that $F$, represented as a function of $x_{1}$ (we have already fixed other variables), is equal to
$$f\left(x_{1}\right)=(n-1) x_{1}^{2}-2\left(\sum_{i=2}^{n} x_{i}\right) x_{1}+c$$
in which $c$ is a constant. Clearly, $f$ is a convex function $\left(f^{\prime \prime}(x)=2(n-1) \geq 0\right)$. According to the above lemma, we conclude that $F$ attains the maximum value if and only if $x_{i} \in\{a, b\}$ for all $i \in\{1,2, \ldots, n\}$. Suppose that $k$ numbers $x_{i}$ are equal to $a$ and $(n-k)$ numbers $x_{i}$ are equal to $b$. In this case, we have
$$F=n\left(\sum_{i=1}^{n} x_{i}^{2}\right)-\left(\sum_{i=1}^{n} x_{i}\right)^{2}=n k a^{2}+n(n-k) b^{2}-(k a+(n-k) b)^{2}=k(n-k)(a-b)^{2}$$

We conclude that
$$\max (F)=\left\{\begin{array}{l}
m^{2}(a-b)^{2} \text { if } n=2 m, m \in \mathbb{N} \\
m(m+1)(a-b)^{2} \text { if } n=2 m+1, m \in \mathbb{N}
\end{array}\right.$$