I was practicing the problem on Algorithm games , I tried the following problem but couldn’t find the efficient way to do it::
So can you please help me.Here is the problem.
This is the exact link::
http://community.topcoder.com/tc?module=Static&d1=match_editorials&d2=srm228
I assume that you would like to solve this one by yourself, so I will give you a hint: this problem has optimal substructure.
Imagine that you have both solutions for
N-1coins (without the leftmost one and without the rightmost one). Would it be easy to calculate a solution forNcoins then?You can use two related techniques to exploit this property – dynamic programming and its subtype called memoization. The idea is to store a solution to each sub-problem with
Lcoins missing from the left andRcoins missing from the right (use anNxNarray for it). Before solving a sub-problem, check the array to see if you’ve already solved it. You would need to solve at mostN^2/2subproblems to arrive at a solution.Here is pseudocode for a memoized solution:
I remember TopCoder running this problem some time in early 2005 or 2006, but I do not remember enough details to search their problem archive.