Can anyone kindly explain the logic behind this solution???

Okay so I was solving this October cook off question:

I used simple logic. Like straight forward logic. But I got the much expected TLE. My solution is here: (dont even bother reading it’s not worth it… )

So while going through the solutions I found this guy’s answer:

I have no idea what on earth has he done! He has used God knows what algorithm!! Can anybody be a lamb and explain what he has done?? I have been trying to figure it out since forever…

I think this post should be more than sufficient to explain the most common approach followed by most users

Thanks a lot for the link… i din’t know that there was a post already in place