The total mechanical energy of the system at any time t is the sum of the kinetic energy of motion of the ball and the elastic potential energy stored in the spring:

where m is the mass of the ball, v its speed, k the spring constant and x the displacement of the spring with respect its rest position.
Since it is a harmonic motion, kinetic energy is continuously converted into elastic potential energy and vice-versa.
When the spring is at its maximum displacement, the elastic potential energy is maximum (because the displacement x is maximum) while the kinetic energy is zero (because the velocity of the ball is zero), so in this situation we have:

Instead, when the spring crosses its rest position, the elastic potential energy is zero (because x=0) and therefore the kinetic energy is at maximum (and so, the ball is at its maximum speed):

Since the total energy E is always conserved, the maximum elastic potential energy should be equal to the maximum kinetic energy, and so we can find the value of the maximum speed of the ball:

