Stone Game

medium dynamic programming game theory math

Problem

Alice and Bob play with an even number of piles of stones, total odd. On each turn a player takes a whole pile from either end. Both play optimally; Alice goes first. Return true if Alice wins (collects more stones).

Inputpiles = [5, 3, 4, 5]
Outputtrue
Alice takes the last pile (5); whatever Bob does she can guarantee ≥ 10.

def stone_game(piles):
    n = len(piles)
    dp = [[0] * n for _ in range(n)]
    for i in range(n):
        dp[i][i] = piles[i]
    for length in range(2, n + 1):
        for i in range(n - length + 1):
            j = i + length - 1
            dp[i][j] = max(piles[i] - dp[i + 1][j],
                           piles[j] - dp[i][j - 1])
    return dp[0][n - 1] > 0
function stoneGame(piles) {
  const n = piles.length;
  const dp = Array.from({ length: n }, () => new Array(n).fill(0));
  for (let i = 0; i < n; i++) dp[i][i] = piles[i];
  for (let len = 2; len <= n; len++) {
    for (let i = 0; i + len - 1 < n; i++) {
      const j = i + len - 1;
      dp[i][j] = Math.max(piles[i] - dp[i + 1][j],
                          piles[j] - dp[i][j - 1]);
    }
  }
  return dp[0][n - 1] > 0;
}
boolean stoneGame(int[] piles) {
    int n = piles.length;
    int[][] dp = new int[n][n];
    for (int i = 0; i < n; i++) dp[i][i] = piles[i];
    for (int len = 2; len <= n; len++)
        for (int i = 0; i + len - 1 < n; i++) {
            int j = i + len - 1;
            dp[i][j] = Math.max(piles[i] - dp[i + 1][j],
                                piles[j] - dp[i][j - 1]);
        }
    return dp[0][n - 1] > 0;
}
bool stoneGame(vector<int>& piles) {
    int n = piles.size();
    vector<vector<int>> dp(n, vector<int>(n, 0));
    for (int i = 0; i < n; i++) dp[i][i] = piles[i];
    for (int len = 2; len <= n; len++)
        for (int i = 0; i + len - 1 < n; i++) {
            int j = i + len - 1;
            dp[i][j] = max(piles[i] - dp[i + 1][j],
                           piles[j] - dp[i][j - 1]);
        }
    return dp[0][n - 1] > 0;
}
Time: O(n²) Space: O(n²)