I know it should be solved using dynamic programming. I tried to solve it for a while. Implemented it with my idea. But it was giving wrong output for sample test case 2. Don’t know where I went wrong. Need help.

Here is the problem link: Problem

Here is my code: Code