Example 4.2.6 Let $a_{1}, a_{2}, \cdots, a_{n}>0, a_{1}, a_{2}, \cdots, a_{n} \in[0,2]$, and satisfy $a_{1}+a_{2}+\cdots+a_{n}=n$, find the maximum value of the following expression.
$$S=a_{1}^{2}+a_{2}^{2}+\cdots+a_{n}^{2}$$
Solution: Applying the lemma above to the convex function $f(x)=x^{2}$, we get that $S$ reaches its maximum value 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}$. Since $a_{1}, a_{2}, \cdots, a_{n} \in[0,2]$, we must have $0 \leq n-2 k \leq 2$.

If $n=2 m(m \in N)$, then $n-2 k \in[0,2]$, which means $\max S=4 m=2 n$

If $n=2 m+1(m \in N)$, then $n-2 k=1$, which means $\max S=4 m+1=2 n+1$