There are n coins in a line. Two players take turns to take a coin from one of the ends of the line until there are no more coins left. The player with the larger amount of money wins.
Could you please decide the first player will win or lose?
Given array A = [3,2,2]
, return true
.
Given array A = [1,2,4]
, return true
.
Given array A = [1,20,4]
, return false
.
Coins in a Line三步曲的最后一步,搞懂了前面两题的思路这题其实也很简单。与前面不一样的是这次我们可以从左端或者右端取硬币,不确定性比较高。那么只考虑一端还剩多少硬币时不够的,而是考虑剩下i到j的硬币时,先手可以取得的最大价值。可以看到这题其实又是一道典型的区间类DP问题。
定义状态,f[i][j]为还剩i到j的硬币时,先手可以取得的最大价值。
状态转换方程是 f[i][j] = sum[i][j] - min(f[i+1][j],f[i][j-1]).也就是考虑f[i][j]时先手是从左端取还是右端取硬币,从左端取对应 f[i+1][j],从右端取对应f[i][j-1]。
在这两者中f[i][j]中的先手都是后手。所以取其中比较小的值可以获得最大值。其实也可以写成f[i][j] = max(sum[i+1][j]-f[i+1][j] + values[i],sum[i][j-1]-f[i][j-1] + values[j])。但是太繁琐。
这题初始化时,考虑是从两边往中间压缩,所以先初始化区间长度最短的,即f[i][i] = values[i][i]。也可以优化f[i][i+1]= max(values[i],values[i+1])。不先初始化而是留给转换方程求解也可以,但是比较容易爆栈。这题因为采用记忆化搜索的方式,且一次只可以取一个。栈的高度是O(n^2)级别的。时间复杂度为O(n^2).代码如下:
class Solution: # @param values: a list of integers # @return: a boolean which equals to True if the first player will win def firstWillWin(self, values): n = len(values) if n == 2: return True sums = [0] for i in xrange(n): sums.append(sums[-1] + values[i]) dp = [[-1] * n for i in xrange(n)] for i in xrange(n): dp[i][i] = values[i] for i in xrange(n-1): dp[i][i+1] = max(values[i],values[i+1]) return self.search(dp, 0, n-1, sums, values) * 2 > sums[n-1] def search(self, dp, start, end, sums, values): if dp[start][end] > 0: return dp[start][end] left = self.search(dp,start+1, end, sums, values) right = self.search(dp, start, end-1, sums, values) dp[start][end] = sums[end + 1] - sums[start] - min(left, right) return dp[start][end]