Calculating elastic energy constant I ran into a kinetic physics problem:
"A spring is hanging on the ceiling. Let's place an object 'M' at the end of the spring. Yet hold 'M' so the spring doesn't stretch. The distance between the floor and 'M' is 'h'. Now let 'M' be free in the air. The spring stretches as much as 'x'. What is the value of the elastic potential energy constant 'k'? ( k from $F = kx$ and $E = \frac{1}{2}kx^2$ )"
Here are constants for the problem.

$m$ : the mass of 'M'
$g$ : gravity acceleration
$h$ : The initial distance between the floor and 'M'
$x$ : Stretched length of the spring after 'M' is attached.

My approach was:
$$m g h = m g (h - x) + 1/2  kx^2 $$
subtract $mgh$
$$-mgx + 1/2  k x^2 = 0$$
add $mgx$
$$ mgx = 1/2 kx^2$$
factor by $(1/2  x^2)$
$$k = (2mg)/x$$
However the official answer says I'm wrong.
The official answer says I should get $k$ in the relation of Force.
$$mg = kx$$
factor by $x$
$$k = (mg)/x$$
Why do I get two different values of k? I asked my school assistant and he doesn't know why but you can use two different methods separately depending on the situation. He was also puzzled because,
$$d/dx (mgx - 1/2 kx^2) = mg - kx$$
So the my logic seems to make sense.
Could someone kindly explain why please?
Thank you!
 A: When using "your aproach" you are assuming that the mass is going to move exactly into the equilibrium position and stay still there. Instead, the mass will descend with some velocity till that point and overpass it, and then bounce back and forth like a harmonic oscilator. In real life the oscillation will vanish due to friction after some time, and the mass will stop at the equilibrium point x, but there will be a transient period in which this phenomenon must be accounted.
The expression $\ E = kx^2/2 $, the energy stored in the spring, comes from integrating the variable force F= kx along the downward path, but the work done into the system comes from the gravity acting on the mass. That (constant) force is bigger than kx for any x smaller than the equilibrium point. So there is an extra work done, not stored in the spring, but in the form of kinetic energy of the mass.
Ideally, assuming no friction or damping, your expression should be refrased like
$\ mgh = mg(h-x) + kx^2/2 + mv^2/2 $
The final situation when all the oscillation is damped, is determined only by the equilibrium of forces, so kx = mg. The energy is then less than in the previuos situation: energy is not conserved in the mass-spring system, part of its initial energy is lost into the surrounding environment.
