I am having trouble understanding the reasoning behind the solution to this question on CareerCup.
Pots of gold game: Two players A & B. There are pot
First of all a
and b
represent respectively the maximum gain if start
(respectively end
) is played.
So let explain this line:
int a = coin[start] + min(max_coin(coin, start+2, end), max_coin(coin, start+1, end-1))
If I play start
, I will immediately gain coin[start]
. The other player now has to play between start+1
and end
. He plays to maximize his gain. However since the number of coin is fixed, this amounts to minimize mine. Note that
start+1
I'll gain max_coin(coin, start+2, end)
end
Ill gain max_coin(coin, start+1, end-1)
Since he tries to minimize my gain, I'll gain the minimum of those two.
Same reasoning apply to the other line where I play end
.
Note: This is a bad recursive implementation. First of all max_coin(coin, start+1, end-1)
is computed twice. Even if you fix that, you'll end up computing lots of time shorter case. This is very similar to what happens if you try to compute Fibonacci numbers using recursion. It would be better to use memoization or dynamic programming.