Getting TLE in Valentine Magic Problem ( Need some advise)

I tried to follow the same approach, of greedily choosing the minimum of available options.
Here is my solution,

I belive that the complexity in my code also is O(N**2) as in the original solution with DP.

Please let me know if I am wrong anywhere. Thanks.

You don’t need to run that loop which is causing TLE, instead you can write a much simpler recursion.
Please see I used that recursion in your code https://ide.codingblocks.com/s/209649

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.