Algo-Sim › Dynamic Programming

Stone Game

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

The same score-difference table as Predict the Winner, on an even number of piles with an odd total, where a parity argument shows Alice always wins.

Problem

An even number of piles of stones sit in a row, and the total number of stones is odd, so there are no ties. Alice and Bob take turns, Alice first; each turn the player takes the whole pile at either end of the row. Both play optimally. Return true if Alice ends with more stones than Bob.

Constraints

Edge cases to test

Follow-up questions

Why does Alice always win?
With an even number of piles she can take all even-indexed or all odd-indexed piles; one set is larger since the total is odd.
What if the number of piles is odd?
The parity argument fails; fall back to the interval DP of Predict the Winner.

Solution

Java

public 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, j = len - 1; j < n; i++, j++) {
            dp[i][j] = Math.max(piles[i] - dp[i + 1][j], piles[j] - dp[i][j - 1]);
        }
    }
    return dp[0][n - 1] > 0;
}

Python

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

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool stoneGame(vector<int> &piles) {
        int n = int(piles.size());
        vector<vector<int>> dp(n, vector<int>(n));
        for (int i = 0; i < n; i++)
            dp[i][i] = piles[i];
        for (int len = 2; len <= n; len++) {
            for (int i = 0, j = len - 1; j < n; i++, j++) {
                dp[i][j] = max(piles[i] - dp[i + 1][j], piles[j] - dp[i][j - 1]);
            }
        }
        return dp[0][n - 1] > 0;
    }
};

More Dynamic Programming problems