S is compact iff every continuous $f: S \to \mathbb{R}$ has a maximum

Given a set $S\subseteq \mathbb{R}$ I have to prove that $S$ is compact iff every continuous function $f:S\to \mathbb{R}$ has a maximum.

$\Rightarrow$) $S$ is compact $\implies f(S)$ compact $\iff f(S)$ closed and bounded. Every closed and bounded subset of $\mathbb{R}$ has maximum and minimum.

I have few problems with the other part of the proof. In order to show that S is compact I tried to use the following theorem:

Let $f$ be a function $f:X \to Y$. If $Y$ is compact and $f^{-1}(y)$ is compact $\forall y \in Y$, then $X$ is also compact.

but I fail to prove that $X=f^{-1}(\{y\})$ is compact. I know that it's closed because f is continuous, so the preimage of the closed set $\{y\}$ is closed, but how to prove that it's bounded?

If $S$ is not compact, then it is unbounded or it is not closed. So:
• if $S$ is unbounded, take $f(x)=\lvert x\rvert$;
• if $S$ is not closed, let $a\in\overline S\setminus S$ and take $f(x)=\frac1{\lvert x-a\rvert}$.
In both cases, $f$ is unbounded above and therefore it has no maximum.
if $S$ is not bounded then the absolute value function is a counterexample.
If $S$ is missing limit point $c$ then $f(x)=\frac{1}{|c-x|}$ is a counterexample. So it must be closed and bounded.