Optimal Strategy for a Game

Pattern: Partition and interval DP

medium

Two players take coins from either end of a row. dp[i][j] is the most the player to move can secure from coins i..j: the segment's total minus the best the opponent can then get, so take whichever end leaves the opponent less.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Coins in a row; two players alternately take a coin from either end, both playing as well as possible. Return the most money the first player can collect.

Think first

  • What does the opponent do after your move?
  • How does that relate to the segment's total?
  • In what order are segments filled?

Hints

    Brute force, and why it fails

    Recursion over both choices at every step: 2ⁿ.

    The key insight

    Every position of the game is a segment (i, j), and there are only n² of them.

    Dry run

    [5, 3, 7, 10]. Taking 10 leaves [5, 3, 7], where the opponent secures 10.

    Step 1 of 2

    The plan

    dp[i][i] = a[i]
    dp[i][j] = sum(i..j) - min(dp[i+1][j], dp[i][j-1])
    

    Complexity

    Time
    O(n²)
    Space
    O(n²)

    Every segment once with prefix sums.

    Edge cases

    • Two coins: the larger.
    • Equal coins: half.
    • One coin.
    I've built my logic, show the code

    Java

    class Solution {
        public int maximumAmount(int[] arr) {
            int n = arr.length;
            int[][] dp = new int[n][n];             // dp[i][j]: the most the player to move can secure from arr[i..j]
            for (int len = 1; len <= n; len++)
                for (int i = 0; i + len - 1 < n; i++) {
                    int j = i + len - 1;
                    int total = 0;
                    for (int k = i; k <= j; k++) total += arr[k];
                    int afterLeft = i + 1 <= j ? dp[i + 1][j] : 0, afterRight = i <= j - 1 ? dp[i][j - 1] : 0;
                    dp[i][j] = total - Math.min(afterLeft, afterRight);   // leave the opponent the worse of the two remainders
                }
            return dp[0][n - 1];
        }
    }

    C++

    class Solution {
    public:
        int maximumAmount(vector<int>& arr) {
            int n = static_cast<int>(arr.size());
            vector<vector<int>> dp(n, vector<int>(n, 0));   // the most the player to move can secure from arr[i..j]
            vector<int> pre(n + 1, 0);
            for (int i = 0; i < n; i++) pre[i + 1] = pre[i] + arr[i];
            for (int len = 1; len <= n; len++)
                for (int i = 0; i + len - 1 < n; i++) {
                    int j = i + len - 1, total = pre[j + 1] - pre[i];
                    int afterLeft = i + 1 <= j ? dp[i + 1][j] : 0, afterRight = i <= j - 1 ? dp[i][j - 1] : 0;
                    dp[i][j] = total - min(afterLeft, afterRight);   // leave the opponent the worse of the two remainders
                }
            return dp[0][n - 1];
        }
    };

    Python

    class Solution:
        def maximumAmount(self, arr: list[int]) -> int:
            n = len(arr)
            pre = [0]
            for x in arr:
                pre.append(pre[-1] + x)
            dp = [[0] * n for _ in range(n)]        # dp[i][j]: the most the player to move can secure from arr[i..j]
            for length in range(1, n + 1):
                for i in range(n - length + 1):
                    j = i + length - 1
                    after_left = dp[i + 1][j] if i + 1 <= j else 0
                    after_right = dp[i][j - 1] if i <= j - 1 else 0
                    dp[i][j] = pre[j + 1] - pre[i] - min(after_left, after_right)   # leave the opponent the worse remainder
            return dp[0][n - 1]

    Common mistakes

    • Greedily taking the larger end.
    • Forgetting the opponent plays well.

    Similar problems