Your problem can be solved in linear time in the length of the input string.
Let $s=s_1s_2s_3\ldots$ be your input string. For $0<i\le j \le |s|$, let $n(i,j,c)$ be the number of occurrences of $c$ in $s_i s_{i+1} \dots s_j$.
Let $m^*$ be the measure of an optimal solution. Now guess the values of $c_1$ and $c_2$ achieving $m^*$ (there are only $26^2$ choices) and consider the auxiliary problem of computing two indices $i(c_1, c_2)$, $j(c_1, c_2)$ that maximize $n(i(c_1, c_2),j(c_1, c_2),c_1) - n(i(c_1, c_2),j(c_1, c_2),c_2)$. Let $m(c_1,c_2)$ be the value of this maximum.
The auxiliary problem can be solved by noticing that each occurrence of $c_1$ in $s_i s_{i+1} \dots s_j$ contributes $1$ to the above quantity while each occurrence of $c_2$ contributes $-1$ (other characters contribute $0$).
Then, this auxiliary problem is equivalent to the maximum subarray problem, which can be easily solved in time $O(|s|)$.
Among all guesses, pick the one maximizing $m(c_1, c_2)$ and return $j(c_1, c_2) - i(c_1, c_2) + 1$.
To see that this algorithm is correct, consider any guess $c_1, c_2$ and let $i=i(c_1, c_2)$ and $j=j(c_1, c_2)$. Notice that if we choose $c^*_1$ and $c^*_2$ as (one of) the most and least frequent characters in $s_i, \dots, s_j$, we must have $m^* \ge n(i, j, c_1^*) - n(i, j, c_2^*) \ge n(i, j, c_1) - n(i, j, c_2) = m(c_1,c_2)$. In other words, $m(c_1,c_2)$ is always a lower bound to $m^*$.
Consider now the case in which your guess of $c_1$ and $c_2$ was correct (i.e., $c_1$ and $c_2$ are the most and less frequent occurring characters in an optimal solution, respectively). Since the optimal substring induces a feasible contiguous subarray for the auxiliary problem with measure $m^*$, we must have $m(c_1, c_2) \ge m^*$, thus implying $m(c_1, c_2)=m^*$.