leetcode877. Stone Game-Game Theory

877. Stone Game

Difficulty: medium

Alex and Lee are playing games with piles of stones. The even-numbered piles of stones are lined up , and each pile has a positive integer number of stones piles[i].

The game is decided by who has the most stones. The total number of stones is odd, so there is no tie.

Alex and Lee take turns, and Alex starts first. Each round, the player takes the entire pile of stones from the beginning or end of the row. This situation continues until there are no more piles of stones, at which point the player with the most stones in his hand wins.

Assume that both Alex and Lee are at their best and return when Alex wins the game and return truewhen Lee wins the game false.

Example:

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

prompt:

  1. 2 <= piles.length <= 500
  2. piles.length Is an even number.
  3. 1 <= piles[i] <= 500
  4. sum(piles) It is odd.

solution

This problem is a math problem or game theory problem, and the first hand is sure to win.
You can ensure that you get all the odd or even digits first, so Alex starts the game and counts out which is the greater the sum of the odd and even digits, and then he finishes. So the program doesn't need to do anything else, just return true.
(Of course, you can write this process, but it is not necessary. If you don’t know the truth, you have to write a recursion or DP)

Guess you like

Origin blog.csdn.net/qq_45268474/article/details/108432027