Sherlock and Cost hackerrank

Pardon me if this question is elementary but I am new to dynamic programming
(https://www.hackerrank.com/challenges/sherlock-and-cost/problem)

I came up with a recursive solution for this problem (https://ideone.com/DU8L0B)
but i am having a hard time memoizing this , later also came up with another recursive solution(https://ideone.com/97THoo)(not very different from the previous one), but i was not able to memoize this again, everytime the output of the memoized solution is wrong…
you you can see my efforts to memoize in the commented section of both the codes

It would be really appreciated if someone will memoize the code, or maybe even explain or help me memoize this…

I am new to dp problems so it would be amazing if someone will give me a bit detailed answer :slight_smile:

2nd memoized solution : https://ideone.com/McZzkr