Logic behind SPOJ ASSIGN problem

dynamic-programming

#1

I am trying to understand the solution here.I am able to understand the bitmask,but unable to understand the logic.Any one please explain the logic.