TITLE: Existence of a continuous function which does not achieve a maximum.
QUESTION [13 upvotes]: Suppose $X$ is a non-compact metric space. Show that there exists a continuous function $f: X \rightarrow \mathbb{R}$ such that $f$ does not achieve a maximum.

I proved this assertion as follows:
If $X$ is non-compact, there exists a sequence which has no converging subsequence. Therefore, the set $E$ of elements of this sequence is infinite and has no limit points. Therefore, in the induced topology, $E$ is a countable discrete space. Let $e_n$ be a enumeration of $E$. Define $f: E \rightarrow \mathbb{R}$ as $f(e_n)=n$. Since $E$ is discrete, $f$ is continuous. By Tietze (note that $E$ is closed in $X$), there exists a continuous function $g: X \rightarrow \mathbb{R}$ which extends $f$. But $f$ is unbounded, then so is $g$, and $g$ does not achieve a maximum. $\square$
My first question is: Is everything in the proof fine?
Now, my second question is: Can you provide me a proof which is more elementary? (Not using Tietze, for example. This exercise is just after the definition of compactness. I suppose this proof is not what was intended.)
And my third question is: Does the proposition hold for arbitrary topological spaces? If not, can you provide a counter-example?

REPLY [8 votes]: Here is an explicit and elementary construction, using only the fact that a metric space is compact iff every sequence has an accumulation point.  Let $(x_n)$ be a sequence in $X$ with no accumulation point, and define $g(x)=\inf_n d(x,x_n)+1/n$ and $f(x)=1/g(x)$.  It is easy to see that $g(x)=0$ iff $x$ is an accumulation point of $(x_n)$, so $g$ is never $0$ and $f$ is defined on all of $X$.  Moreover, $f(x_n)\geq n$, so $f$ is unbounded.  Finally, it is straightforward to check that $g$ is continuous, and hence so is $f$.