Answer:
spring force = -K × x , where X is elongation or compression in the spring. ( -) sigh shows that the spring force is opposite to the applied force to cause extension.
Potential energy = work done by spring force = integration of Force.
integrate the force (-K × x) over distance 0 to x .
U = 1/2 K × X^2 ( for elongation)
U = -1/2 × K × X^2 ( for compression)