I have approached this problem using DP and I have written the code and I think my logic is correct as its working for few sample inputs of my own. But I am getting wrong answer for all test cases except one. I am sharing the code, please check if my logic is flawed or my code.
Code link - https://ide.codingblocks.com/s/89719