Building on Pietro Majer's answer to you previous question for a change, consider the following:
Let $g: [0,\infty) \to \mathbb{R}$ be the unique continuous function such that $g(0)=0$, $g'(x) = 1$ for $x \in [\frac{1}{2k},\frac{1}{2k+1}]$ and $g'(x) = -1$ for $x \in [\frac{1}{2k},\frac{1}{2k+1}]$ for any $k\in\mathbb{N}$ as well as (arbitrarily) $g'(x) = 1$ for $x > 1$. Its a bit tedious to write it down, but one can do so even explicitly.
But even without, note that as the intervals get larger, consecutive local maxima have to be ascending and minima have to be descending. In particular this means that maxima are always positive and minima negative. At the same time the distance from maximum to minimum and vice versa is about $\frac{1}{k}-\frac{1}{k+1} = \frac{1}{k(k+1)}$ near $x\approx\frac{1}{k}$. We thus find that $|g(x)| < 2x^2$ and obviously $|g'(x)| = 1$ almost everywhere.
Now for any closed set $C\subset \mathbb{R}^n$, consider $f(x) := g(\operatorname{dist}(x,C))$. It is known that $|\nabla \operatorname{dist}(x,C)| =1$ almost everywhere in $\mathbb{R}^n\setminus C$. Assuming that none of the nonzero level-sets of the distance function is of positive $n$-dimensional measure¹, thus $|\nabla f| = 1$ almost everywhere in $\mathbb{R}^n\setminus C$ again.
In contrast, for any $x_0 \in C$, we have $|f(x_0)-f(x)| = |f(x)| \leq g(|x_0-x|) \leq 2|x_0-x|^2$ and thus $f'(x_0) = 0$.
So again if $C$ is chosen as some fractal set of arbitrary Hausdorff-dimension with $\mathcal{H}^n(C) =0$, then this shows that the maximal dimension is $n$ itself.
¹I do not think this can actually ever happen for the distance function, but I could not come up with a quick proof on the fly, so I will only note that it certainly can be avoided for any Cantor-type set.