The elastic potential energy of a spring is: [tex]U= \frac{1}{2}kx^2 [/tex] where k is the spring constant and x is the displacement.
The spring constant k can be computed as the ratio between the force applied F and the displacement x: [tex]k= \frac{F}{x} [/tex] But in our problem, the force that stretches the spring is the weight (mg) of the mass m that hangs from the spring, so: [tex]k= \frac{mg}{x} [/tex]
Therefore, substituting k into the original formula, we can re-write the elastic potential energy as: [tex]U= \frac{1}{2} ( \frac{mg}{x} )x^2 = \frac{1}{2}mgx [/tex]