This is a proof of the discrete case for Michael Rozenberg's reply, assuming $n\ge 2$ and therefore $M>1$.
Consider a cyclic word $x$ on $\{a,b\}^n$ maximizing $f$. We can write $f(x)$ as a linear function of the counts of the $n$ cyclic bigrams $x_i x_{(i+1)\bmod n}$:
$$f(x) = n_{aa} w(a,a) + n_{ab} w(a,b) + n_{ba} w(b,a) + n_{bb} w(b,b)$$
where $w(s,t)=\frac{s^2}{t} - M s$.
Because $M>1$, $w(b,b) < w(a,a)$ therefore $x\ne b^n$ and if $x$ contained an instance of $bb$, we could increase $f(x)$ by replacing it with $b$ and inserting another $a$ next to any $a$. Thus $n_{bb}=0$.
And because there are as many $ba$ bigrams as $ab$, we have:
$$f(x) = \left(n-2n_{ab}\right) w(a,a) + n_{ab} \left(w(a,b)+w(b,a)\right)$$
This is a linear function of $n_{ab}$ so the maximum is reached when $x$ is either of the form $a^n$ or $(ab)^* a?$. The former is never maximal because $M>1$, therefore Michael Rozenberg's construction is optimal.