Let $a_{0}, a_{1}, a_{2}, \ldots$ be a sequence of real numbers such that $a_{0}=0, a_{1}=1$ and for all $n \geqslant 2$ there exists $1 \geqslant k \geqslant n$ such that

$$
a_{n}=\frac{a_{n-1}+\cdots+a_{n-k}}{k}
$$

What is the maximum value of $a_{2018}-a_{2017}$?
The answer is $\frac{2016}{2017^{2}}$. To see that $\frac{2016}{2017^{2}}$ can be achieved, consider the sequence

$$
a_{0}=0, \quad a_{1}=\cdots=a_{2016}=1, \quad a_{2017}=1-\frac{1}{2017}, \quad a_{2018}=1-\frac{1}{2017^{2}}
$$

Now let's show that this is optimal. Consider the auxiliary sequences:

$$
u_{n}=\min _{k} \frac{a_{n-1}+\cdots+a_{n-k}}{k} \quad \text { and } \quad v_{n}=\max _{k} \frac{a_{n-1}+\cdots+a_{n-k}}{k} \text {. }
$$

The first thing to note is that we can assume $a_{n} \in\left\{u_{n}, v_{n}\right\}$ for all $n$, indeed if we are given $a_{0}, \cdots, a_{n-1}$ as well as the integers $k$ defining $a_{n+1}, \cdots a_{2018}$, then $a_{2018}-a_{2017}$ is an affine function of $a_{n}$, so we can assume $a_{n} \in\left\{u_{n}, v_{n}\right\}$.

Moreover, we can assume that $a_{2017}=u_{2017}$ and $a_{2018}=v_{2018}$. Now we need to study $v_{n}-u_{n}$. For this, let's prove the following two facts:

Fact 1. If $a_{n}=v_{n}$, then $v_{n+1}-u_{n+1} \leq \frac{n}{n+1} \cdot\left(v_{n}-u_{n}\right)$.

Proof. In this case $v_{n+1}=v_{n}$. Thus:

$$
\begin{aligned}
u_{n+1} & =\min _{k} \frac{v_{n}+a_{n-1}+\cdots+a_{n-k}}{k+1} \\
& =\min _{k}\left(\frac{1}{k+1} \cdot v_{n}+\frac{k}{k+1} \cdot \frac{a_{n-1}+\cdots+a_{n-k}}{k}\right) \\
& \geq \min _{k}\left(\frac{1}{n+1} \cdot v_{n}+\frac{n}{n+1} \cdot \frac{a_{n-1}+\cdots+a_{n-k}}{k}\right) \\
& =\frac{1}{n+1} v_{n}+\frac{n}{n+1} u_{n}
\end{aligned}
$$

Thus $v_{n+1}-u_{n+1} \leq \frac{n}{n+1} \cdot\left(v_{n}-u_{n}\right)$ as desired.

Fact 2. If $a_{n}=u_{n}$, then $v_{n+1}-u_{n+1} \leq \frac{n-1}{n} \cdot\left(v_{n}-u_{n}\right)$.

Proof. In this case $u_{n+1}=u_{n}$. Thus:

$$
\begin{aligned}
v_{n+1} & =\max _{k} \frac{u_{n}+a_{n-1}+\cdots+a_{n-k}}{k+1} \\
& =\max _{k}\left(\frac{1}{k+1} \cdot u_{n}+\frac{k}{k+1} \cdot \frac{a_{n-1}+\cdots+a_{n-k}}{k}\right) \\
& \leq \max _{k}\left(\frac{1}{n} \cdot u_{n}+\frac{n-1}{n} \cdot \frac{a_{n-1}+\cdots+a_{n-k}}{k}\right) \\
& =\frac{1}{n} u_{n}+\frac{n-1}{n} v_{n}
\end{aligned}
$$

Thus $v_{n+1}-u_{n+1} \leq \frac{n-1}{n} \cdot\left(v_{n}-u_{n}\right)$ as desired.

We can now conclude. Note that $v_{n+1}-u_{n+1} \leq \frac{n}{n+1} \cdot\left(v_{n}-u_{n}\right)$ for $n \in$ $\{2,3, \ldots, 2016\}$ and $v_{n+1}-u_{n+1} \leq \frac{n-1}{n} \cdot\left(v_{n}-u_{n}\right)$ for $n=2017$. Thus

$$
\begin{aligned}
a_{2018}-a_{2017}=v_{2018}-u_{2017} & =v_{2018}-u_{2018} \\
& \leq \frac{2}{3} \cdot \frac{3}{4} \cdots \frac{2016}{2017} \cdot \frac{2016}{2017} \cdot\left(v_{2}-u_{2}\right) \\
& =\frac{2016}{2017^{2}}
\end{aligned}
$$

which concludes the proof.