$L=T-V=\frac{1}{2}\frac{m}{3}{\dot{x}}^{2}+\frac{1}{2}M{\dot{x}}^{2}-\frac{1}{2}k{x}^{2}-\frac{mgx}{2}-Mgx$

where $mgx/2$ refers to gravitational potential energy of ideal spring. But I do not get why it's $mgx/2$ instead of $mgx$. What is the reason?