[LeetCode] Stone Game

877. Stone Game

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
int dp[501][501];
public:
bool stoneGame(vector<int>& piles) {
int n = piles.size();
for(int i = 0; i < n; i++) dp[i][i] = piles[i];
for(int diff = 1; diff < n; diff++) {
for(int i = 0; i < n - diff; i++) {
dp[i][i + diff] = max(piles[i] + dp[i + 1][i + diff], piles[i + diff] + dp[i][i + diff - 1]);
}
}
return dp[0][n - 1] > 0;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/23/PS/LeetCode/stone-game/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.