How to solve https://www.codechef.com/CDVA17/problems/CDVA1707/ problem?

How to solve this problem?
https://www.codechef.com/CDVA17/problems/CDVA1707/

I am trying to seek solution for a generalized problem. Kindly provide me an explanation for the generalized version of this problem