leetcode-1140-Stone Game II
问题
Alex and Lee continue their games with piles of stones. There are a 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.
Alex and Lee take turns, with Alex starting first. Initially, M = 1
.
On each player’s turn, that player can take all the stones in the first X
remaining piles, where 1 <= X <= 2M
. Then, we set M = max(M, X)
.
The game continues until all the stones have been taken.
Assuming Alex and Lee play optimally, return the maximum number of stones Alex can get.
Example 1:
1 | Input: piles = [2,7,9,4,4] |
Constraints:
1 <= piles.length <= 100
1 <= piles[i] <= 10 ^ 4
分析
思路: 使用动态规划,$f(i,j)$ 表示当从下标为 $i$ 的石块开始取,且 $m = j$ 时,先取的人能够获得的最大石块数。则有
$$
f(i,j) = sum(A[i]+..A[i+k-1]) + suffixSum(i+k) - f(i+k, min(max(k, m), n));
$$
限制 $m$ 的最大值为 $n$,(n/2 + 1)也行。
代码
1 | // 自顶向下 |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/03/28/leetcode-1140/
License: 知识共享署名-非商业性使用 4.0 国际许可协议