Coins in a Line II
Description:
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?
Given values array A = [1,2,2], return true. Given A = [1,2,4], return false.
分析:
假设dp[i]
表示从i到end能取到的最大value。
当我们走到 i
时,有两种选择:(1) 取values[i]
。(2) 取values[i] + values[i+1]
。
如果取
values[i]
,对手的选择有values[i+1]
或者values[i+1] + values[i+2]
剩下的最大总value分别为dp[i+2]
或dp[i+3]
,对手也是理性的所以要让我们得到最小value。所以value1 = values[i] + min(DP[i+2], DP[i+3])
。如果取
values[i]
和values[i+1]
,同理value2 = values[i] + values[i+1] + min(dp[i+3], dp[i+4])
。
最后状态转移方程:dp[i] = max(value1, value2)
。
Code:
1 | class Solution { |