leetcode 877 stone game

1. Problem description

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.

Alex and Lee are playing games with piles of stones. The even-numbered piles of stones are arranged in a row, and each pile has a positive integer number of stones[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 the 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.

Assuming that both Alex and Lee are at their best, return true when Alex wins the game, and false when Lee wins the game.

Input: [5,3,4,5]
Output: true
Explanation:
Alex starts first and can only take the first 5 or the last 5 stones.
Suppose he took the first 5, this line becomes [3,4,5].
If Lee takes the first 3, then the rest is [4,5], and Alex takes the last 5 and wins 10 points.
If Lee takes the last 5, then the remaining is [3,4], Alex takes the last 4 and wins 9 points.
This shows that taking the first 5 stones is a winning move for Alex, so we return true.

2. Solution

This question looks very complicated, but it is actually very easy...
Pay attention to the two important conditions above: the number of piles of stones is even, and the total number is odd.
Take the test example to analyze, there are a total of 4 piles of stones, and Alex will either take the first and third piles (the array index starts with 1), or the second and fourth piles. In other words, either he takes the odd pile or the even pile. Because the total is an odd number, the number of stones in the odd pile and the even pile must be inconsistent. Then, Alex only needs to observe in advance whether there are more stones in odd piles or even piles, and then select the corresponding strategy, and he will definitely win!

The final solution is

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

Guess you like

Origin blog.csdn.net/bitcarmanlee/article/details/114103301