Example 4.2.6. Let $a_{1}, a_{2}, \ldots, a_{n}$ be positive real numbers belonging to $[0,2]$ such that $a_{1}+a_{2}+\ldots+a_{n}=n$. Find the maximum value of
$$S=a_{1}^{2}+a_{2}^{2}+\ldots+a_{n}^{2}$$
Solution. Applying the above lemma to the convex function $f(x)=x^{2}$, we get that $S$ attains the maximum if and only if $k$ numbers are equal to 2 and $n-k-1$ numbers are equal to 0. In this case, we have $S=4 k+(n-2 k)^{2}$. Because $a_{1}, a_{2}, \ldots, a_{n} \in[0,2]$, we must have $0 \leq n-2 k \leq 2$.

If $n=2 m(m \in \mathbb{N})$ then $n-2 k \in\{0,2\}$. That implies $\max S=4 m=2 n$.
If $n=2 m+1(m \in \mathbb{N})$ then $n-2 k=1$. That implies $\max S=4 m+1=2 n+1$.