Understanding solution to finding optimal strategy for game involving picking pots of gold

前端 未结 5 2002
深忆病人
深忆病人 2021-02-13 23:50

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

5条回答
  •  悲哀的现实
    2021-02-14 00:08

    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

    • if he plays start+1 I'll gain max_coin(coin, start+2, end)
    • if he plays 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.

提交回复
热议问题