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.
亚历克斯和李用一堆石头玩游戏。 连续排列的偶数堆,每堆都有正整数的石堆[i]。
游戏的目标是以最多的石头结束。 石头总数是奇数,所以没有关系。
亚历克斯和李轮流,亚历克斯首先出发。 每一回合,玩家从行的开头或结尾拿走整堆石头。 这种情况一直持续到没有剩下的堆积为止,此时石头最多的人获胜。
假设Alex和Lee发挥最佳状态,当且仅当Alex赢得比赛时才返回True。
Example 1:
Input: [5,3,4,5]
Output: true
Explanation:
Alex starts first, and can only take the first 5 or the last 5.
Say he takes the first 5, so that the row becomes [3, 4, 5].
If Lee takes 3, then the board is [4, 5], and Alex takes 5 to win with 10 points.
If Lee takes the last 5, then the board is [3, 4], and Alex takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alex, so we return true.
输入:[5,3,4,5]
输出:true
说明:
亚历克斯首先开始,只能拿前5或后5。
假设他取了前5个,这样行就变成了[3,4,5]。
如果李拿下3分,那么董事会是[4,5],亚历克斯以5分赢得10分。
如果李拿下最后5分,那么董事会是[3,4],亚历克斯以4分赢得9分。
这证明了前5名是亚历克斯的胜利之举,所以我们回归真实。
Note:
2 <= piles.length <= 500
piles.length
is even.1 <= piles[i] <= 500
sum(piles)
is odd.
python实践
- 总结规律,Alex总是会赢
class Solution:
def stoneGame(self, piles):
return True
- 这是一个数学问题,要注意的有两点,第一,有偶数堆,第二,总数为奇数,不存在平局。所以这样想,如果有2堆,亚历克斯选一个多的,肯定赢了,如果有4堆,平分两堆,亚历克斯每两堆中先选一堆多的,最后是亚历克斯赢,推广到2*N 堆,按照两堆来分,亚历克斯每两堆中选择一堆多的,所以无论怎么样,亚历克斯都会赢的。