Conserve momentum before and after collision. The kinetic energy of blocks after collision is converted into elastic potential energy of the spring at the instant of maximum compression. Maximum compression is equal to amplitude of resulting SHM.
Assuming the collision to last for a small interval only, we can apply the principle of conservation of momentum. The common velocity after the collision is v/2 . The kinetic energy

also the total energy of vibration as the spring is unstretched at this moment. If the amplitude is A, the total energy can also be written as 1/2 kA2.
