Coins in a Line II
Question
There are n coins with different value in a line. Two players take turns to take one or two coins from left side until there are no more coins left. The player who take the coins with the most value wins.
Could you please decide the first player will win or lose?
Example
Given values array A = [1,2,2], return true.
Given A = [1,2,4], return false.
Tags
Dynamic Programming Array Game Theory
Related Problems
Hard Coins in a Line III 30 % Medium Coins in a Line
Analysis
动态规划4要素
State:
dp[i] 现在还剩i个硬币,现在当前取硬币的人最后最多取硬币价值
Function:
i 是所有硬币数目
sum[i] 是后i个硬币的总和
dp[i] = sum[i]-min(dp[i-1], dp[i-2])
Intialize:
dp[0] = 0
dp[1] = coin[n-1]
dp[2] = coin[n-2] + coin[n-1]
Answer:
dp[n]
可以画一个树形图来解释:
也就是说,每次的剩余硬币价值最多值dp[i],是当前所有剩余i个硬币价值之和sum[i],减去下一手时对手所能拿到最多的硬币的价值,即 dp[i] = sum[i] - min(dp[i - 1], dp[i - 2])
Solution
Reference
Last updated