Example 4 Let $x_{1}, x_{2}, \cdots, x_{n}$ take values in some interval of length 1, denote $x=\frac{1}{n} \sum_{j=1}^{n} x_{j}$, $y=\frac{1}{n} \sum_{j=1}^{n} x_{j}^{2}$, find the maximum value of $f=y-x^{2}$. (High School Mathematics League Simulation)
Let $x_{1}, x_{2}, \cdots, x_{n} \in[a, a+1](a \in \mathbf{R})$, when $n=1$, $f=0$, at this time $f_{\max }=0$.

When $n>1$, if we fix $x_{2}, x_{3}, \cdots, x_{n}$, then
$$\begin{aligned}
f & =y-x^{2}=\frac{1}{n} \sum_{j=1}^{n} x_{j}^{2}-\left(\frac{1}{n} \sum_{j=1}^{n} x_{j}\right)^{2} \\
& =\frac{n-1}{n^{2}} x_{1}^{2}-\left(\frac{2}{n^{2}} \sum_{j=2}^{n} x_{j}\right) x_{1}+\frac{1}{n} \sum_{j=2}^{n} x_{j}^{2}-\left(\frac{1}{n} \sum_{j=2}^{n} x_{j}\right)^{2}
\end{aligned}$$

Since $f$ is a quadratic function of $x_{1}$ on the interval $[a, a+1]$, and the coefficient of the quadratic term $\frac{n-1}{n^{2}}>0$, we have
$$f \leqslant \max \left\{f\left(a, x_{2}, x_{3}, \cdots, x_{n}\right), f\left(a+1, x_{2}, x_{3}, \cdots, x_{n}\right)\right\}$$

This indicates that when $f$ reaches its maximum value, there must be $x_{1} \in\{a, a+1\}$. By symmetry, when $f$ reaches its maximum value, there must be $x_{1}, x_{2}, \cdots, x_{n} \in\{a, a+1\}$, i.e.,
$$f \leqslant \max _{x_{i} \in\{a, a+1\}, 1 \leqslant i \leqslant n}\left\{f\left(x_{1}, x_{2}, x_{3}, \cdots, x_{n}\right)\right\}$$

Assume that when $f$ reaches its maximum value, $x_{1}, x_{2}, \cdots, x_{n}$ have $s$ values of $a$ and $n-s$ values of $a+1$, then
$$\begin{aligned}
& \max _{x_{i} \in\{a, a+1\}, 1 \leqslant i \leqslant n}\left\{f\left(x_{1}, x_{2}, x_{3}, \cdots, x_{n}\right)\right\} \\
= & \frac{1}{n}\left[s a^{2}+(n-s)(a+1)^{2}\right]-\frac{1}{n^{2}}[s a+(n-s)(a+1)]^{2} \\
= & \frac{1}{n^{2}} s(n-s) \leqslant\left\{\begin{array}{cl}
\frac{n^{2}-1}{4 n^{2}} & (n \text { is odd }) ; \\
\frac{1}{4} & (n \text { is even })
\end{array}\right.
\end{aligned}$$

When $x_{1}, x_{2}, \cdots, x_{n}$ have $\left[\frac{n+1}{2}\right]$ values of $a$ and $n-\left[\frac{n+1}{2}\right]$ values of $a+1$, the equality holds, hence
$$f_{\max }=\left\{\begin{array}{cl}
\frac{n^{2}-1}{4 n^{2}} & \text { ( } n \text { is odd }) ; \\
\frac{1}{4} & \text { ( } n \text { is even }) .
\end{array}\right.$$