国庆长假,水一题
题目
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.
解法一
第一种解法是使用动态规划,注意到每次Alex和Lee的操作都是从piles的头或尾取走一个最大的数,那么就可以把问题分解到多个子问题上分别来解决。
先构建一个数组存储piles的备份,以及一个二维数组存储各个子问题的解:
1 | vector<vector<int>> dparr; |
下面是dp的具体实现,这里将Lee的操作视为从Alex的得分中扣除,最后只要Alex的得分大于零则Alex胜利:
1 | int dp(int low, int high){ |
解法二
让我们回到问题:数组中一共有偶数个元素,Alex先选,Lee后选。那么假设数组有2n个元素,如果Alex第一次选择了元素1,则Lee可以选择2或2n,在之后Alex可以选择3、2n或者2、2n-1,以此类推。也就是说,可以保证Alex一定能够选到所有奇数位置的元素或是所有偶数位置的元素,那么只要一开始知道奇数位置元素之和与偶数位置元素之和哪个更大,就能保证Alex胜利,所以实际上这道题我们只需要:
1 | return true; |
就能够通过。