I understood the problem. But I don't know how to implement. I am also unable to do plain brute-force. Any hint will be helpful :)
Here M <=18, so it gives a chance to do DP with Bitmask :)
Keshav , is csacademy a good website to study from?