Algo-Sim › Dynamic Programming

Predict the Winner

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

Two players take turns removing a number from either end. Score each interval by the difference the player to move can force, and fill the table by length.

Problem

Two players take turns. On each turn the current player removes either the first or the last number of nums and adds it to their score. Player 1 moves first and both play optimally. Return true if player 1 finishes with a score at least as high as player 2’s (a tie counts as a win for player 1).

Constraints

Edge cases to test

Follow-up questions

Why store a score difference?
The best move maximises "my take − what the opponent then forces": one number per interval, O(n²) states.
How do you get each player’s score?
From the difference d and the total S: player 1 has (S + d)/2.

Solution

Java

public boolean predictTheWinner(int[] nums) {
    int n = nums.length;
    int[][] dp = new int[n][n];
    for (int i = 0; i < n; i++) dp[i][i] = nums[i];
    for (int len = 2; len <= n; len++) {
        for (int i = 0, j = len - 1; j < n; i++, j++) {
            dp[i][j] = Math.max(nums[i] - dp[i + 1][j], nums[j] - dp[i][j - 1]);
        }
    }
    return dp[0][n - 1] >= 0;
}

Python

def predict_the_winner(nums):
    n = len(nums)
    dp = [[0] * n for _ in range(n)]
    for i in range(n):
        dp[i][i] = nums[i]
    for length in range(2, n + 1):
        for i in range(n - length + 1):
            j = i + length - 1
            dp[i][j] = max(nums[i] - dp[i + 1][j], nums[j] - dp[i][j - 1])
    return dp[0][n - 1] >= 0

C++

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

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

More Dynamic Programming problems