leetcode 877 stone game

1.问题描述

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.

亚历克斯和李用几堆石子在做游戏。偶数堆石子排成一行,每堆都有正整数颗石子 piles[i] 。

游戏以谁手中的石子最多来决出胜负。石子的总数是奇数,所以没有平局。

亚历克斯和李轮流进行,亚历克斯先开始。 每回合,玩家从行的开始或结束处取走整堆石头。 这种情况一直持续到没有更多的石子堆为止,此时手中石子最多的玩家获胜。

假设亚历克斯和李都发挥出最佳水平,当亚历克斯赢得比赛时返回 true ,当李赢得比赛时返回 false 。

输入:[5,3,4,5]
输出:true
解释:
亚历克斯先开始,只能拿前 5 颗或后 5 颗石子 。
假设他取了前 5 颗,这一行就变成了 [3,4,5] 。
如果李拿走前 3 颗,那么剩下的是 [4,5],亚历克斯拿走后 5 颗赢得 10 分。
如果李拿走后 5 颗,那么剩下的是 [3,4],亚历克斯拿走后 4 颗赢得 9 分。
这表明,取前 5 颗石子对亚历克斯来说是一个胜利的举动,所以我们返回 true 。

2.解法

这题看上去很复杂,其实很easy…
注意上面的两个重要条件:石头的堆数是偶数,而且总数是奇数。
以测试例子来分析,总共4堆石子,Alex要么拿第1,3堆(数组索引按1开始计算),要么拿第2,4堆。换句话说,要么他拿奇数堆,要么拿偶数堆。因为总数是奇数,所以奇数堆跟偶数堆的石子数量肯定不一致。那么,Alex只需要事先观察是奇数堆的石子多,还是偶数堆的石子多,然后选择相应的策略即可,一定能取胜!

那最后的解法就是

public boolean stoneGame(int[] piles) {
    return true;
}

猜你喜欢

转载自blog.csdn.net/bitcarmanlee/article/details/114103301