leetcode-877-Stone Game
问题
Alex and Lee play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]
.
The objective of the game is to end with the most stones. The total number of stones is odd, so there are no ties.
Alex and Lee take turns, with Alex starting first. Each turn, a player takes the entire pile of stones from either the beginning or the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins.
Assuming Alex and Lee play optimally, return True
if and only if Alex wins the game.
Example 1:
1 | Input: [5,3,4,5] |
Note:
2 <= piles.length <= 500
piles.length
is even.1 <= piles[i] <= 500
sum(piles)
is odd.
分析
思路1: 动态规划,令 $f(i,j)$ 表示从 $a[i..j]$ 这个范围内,先行者能够获得的最大的石块数量。$sum(i, j)$ 表示 $a[i..j]$ 中所有元素的和。则有状态转移方程如下:
$$
f(i,j) = max \{a[i]+sum(i+1,j)-f(i+1,j), a[j]+sum(i,j-1)-f(i,j-1)\};
$$
初始状态令 $f(i,j) = a[i]$. 以区间长度来作为DP的阶段,最终求出$f(0,n-1)$ 的值,然后判断其是否能够大于$sum(0,n-1) $ 的一半。
思路2: 采用数学的方法。在这道题目中石堆的总数是偶数个,并且所有石子个个数是奇数个,那么就只存在,所有下标为偶数的石堆中所包含的石子的总和大于所有下标为奇数的石堆中所有石子的总和,要么小于。那么对于Alice而言,才去某种方案,他总能获取到所有下标为奇数的石堆,或者总能获取到下标为偶数的石堆。所以说,Alice一定是可以赢的。比如让Alice选择的所有石堆都是下标为偶数的石堆,在所有石堆中,Alice先行选择,Alice选择了下标为0的石堆,那么Lee的选择只能从下标为奇数的石堆中进行选择了。那么接下来,Alice又存在了两种选择,下标为偶数的石堆或者下标为奇数的石堆,这么在这个时候,我们再让Alice从下标为偶数的石堆中进行选择,于是Lee又只能从下标为奇数的石堆中进行选择了。依次类推,Alice所有选择的石堆都将是下标为偶数的石堆。同理,Alice也可以选择所有下标都为奇数的石堆。因此,Alice稳赢。
代码1
1 | // DP solution |
代码2
1 | // Math |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/03/23/leetcode-877/
License: 知识共享署名-非商业性使用 4.0 国际许可协议