Prove $f(x)$ is constant.
Let $ I = [a, b] $ be any closed interval and assume, without loss of generality, that $ f $ attains its maximum value $ M $ in the interior; the case where it attains its minimum value instead is similar. Suppose $ f(a) < f(b) $ without loss of generality, I'll obtain a contradiction from this assumption.
Since $ f $ is continuous, $ [a, b] \cap f^{-1}(\{ M \}) $ is a closed and bounded set, therefore it has minimum and maximum values $ x_{\textrm{min}}, \, x_{\textrm{max}} $. If $ x_{\textrm{min}} = a $ then $ f(a) = M $ and this contradicts $ f(a) < f(b) $, so we can assume $ x_{\textrm{min}} > a $.
Now, since $ x_{\textrm{min}} $ is the minimum value for which $ f $ attains its maximum value $ M $, it can't attain the value $ M $ anywhere in the interval $ (a, x_{\textrm{min}}) $. Therefore it must instead attain its minimum value $ m $ on the interval $ [a, x_{\textrm{min}}] $ somewhere in the interior. Similar to the above, take the maximum value such that $ f $ attains its minimum $ m $ there, call it $ y_{\textrm{max}} $. If $ y_{\textrm{max}} = x_{\textrm{min}} $ then $ m = M $ and therefore $ f(a) = m = M $ once more, which yields the same contradiction as above with $ f(a) < f(b) $. Therefore we must have $ y_{\textrm{max}} < x_{\textrm{min}} $, in which case $ f $ attains neither its maximum nor its minimum on $ [y_{\textrm{max}}, x_{\textrm{min}}] $ in the interior, yielding a contradiction.
We conclude that $ f(a) < f(b) $ is impossible, and we can similarly show that $ f(a) > f(b) $ is impossible, so we must have $ f(a) = f(b) $. Since $ a, b $ were arbitrary, it follows that $ f $ is constant.