Optimal Strategy for a Game

Consider a row of n coins of values v1 . . . vn, where n is even. We play a game against an opponent by alternating turns. In each turn, a player selects either the first or last coin from the row, removes it from the row permanently, and receives the value of the coin. Determine the maximum possible amount of money we can definitely win if we move first.

Note: The opponent is as clever as the user.

Let us understand the problem with few examples:

  1. 5, 3, 7, 10 : The user collects maximum value as 15(10 + 5)

  2. 8, 15, 3, 7 : The user collects maximum value as 22(7 + 15)

Does choosing the best at each move gives an optimal solution? No. In the second example, this is how the game can be finished:

  1. …….User chooses 8. …….Opponent chooses 15. …….User chooses 7. …….Opponent chooses 3. Total value collected by user is 15(8 + 7)

  2. …….User chooses 7. …….Opponent chooses 8. …….User chooses 15. …….Opponent chooses 3. Total value collected by user is 22(7 + 15)

So if the user follows the second game state, the maximum value can be collected although the first move is not the best.

class Solution {
    public static int optimalStrategyOfGame(int arr[], int n) {
        // dp[i][j] stores 2 values , 1st -> max possible values for 1st player ,
        // 2nd -> max possible values for second player
        int[][][] dp = new int[n][n][];
        // Base case when i=j , i.e -> only once coin is considered
        for (int i = 0; i < n; i++) {
            dp[i][i] = new int[]{arr[i], 0};
        }
        for (int k = 1; k < n; k++) {
            for (int i = 0; i + k < n; i++) {
                int j = i + k;

                int pickLeftScore = arr[i] + dp[i + 1][j][1];

                int pickRightScore = arr[j] + dp[i][j - 1][1];

                if (pickLeftScore > pickRightScore) {
                    int secondPlayerScore = dp[i + 1][j][0];
                    dp[i][j] = new int[]{pickLeftScore, secondPlayerScore};
                } else {
                    int secondPlayerScore = dp[i][j - 1][0];
                    dp[i][j] = new int[]{pickRightScore, secondPlayerScore};
                }
            }
        }
        return dp[0][n - 1][0];
    }
}

Last updated