Let us consider the table as the reference point of zero potential energy such that the part of the chain on the table has no potential energy.
For potential energy of the hanging part, Cnsider an elementary part of length dl at a distance l from the lower tip of the hanging part The PE of the element is dU=gl dm=gl M/Ldl or U=Mg/L integration(ldl)from L/n to 0 this gives U=-MgL/2n^2
When the last link leaves, The potential energy can be obtained in a similar fashion as above by integrating from L to 0. This gives U'=-MgL/2