Open In App

Optimal Strategy for a Game

Last Updated : 11 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size n which represents 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.

Examples:

Input: arr[] = [5, 3, 7, 10]
Output: 15 -> (10 + 5)
Explanation: The user collects the maximum value as 15(10 + 5). It is guaranteed that we cannot get more than 15 by any possible moves.

 Input: arr[] = [8, 15, 3, 7]
Output: 22 -> (7 + 15)
Explanation: The user collects the maximum value as 22(7 + 15). It is guaranteed that we cannot get more than 22 by any possible moves.

Why greedy algorithm fail here?

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

  • The user chooses 8. 
    The opponent chooses 15. 
    The user chooses 7. 
    The opponent chooses 3. 
    The total value collected by the user is 15(8 + 7)
  • The user chooses 7. 
    The opponent chooses 8. 
    The user chooses 15. 
    The opponent chooses 3. 
    The total value collected by the user is 22(7 + 15)

Note: If the user follows the second game state, the maximum value can be collected although the first move is not the best. 

Using Recursion – O(2^n) Time and O(n) Space

There are two choices:  

  • The user chooses the 'ith' coin with value 'Vi': The opponent either chooses (i+1)th coin or jth coin. The opponent intends to choose the coin which leaves the user with minimum value
    i.e. The user can collect the value Vi + min(maxAmount(i+2, j), maxAmount(i+1, j-1)) where [i+2,j] is the range of array indices available to the user if the opponent chooses Vi+1 and [i+1,j-1] is the range of array indexes available if opponent chooses the jth coin. 
optimal-strategy-for-a-game
  • The user chooses the 'jth' coin with value 'Vj': The opponent either chooses 'ith' coin or '(j-1)th' coin. The opponent intends to choose the coin which leaves the user with the minimum value, i.e. the user can collect the value Vj + min(maxAmount(i+1, j-1), maxAmount(i, j-2) ) where [i, j-2] is the range of array indices available for the user if the opponent picks jth coin and [i+1, j-1] is the range of indices available to the user if the opponent picks up the ith coin.
optimal-strategy-for-a-game-2
C++
// Function to calculate the maximum amount one can collect
// using the optimal strategy from index i to index j
// using recursion

#include <bits/stdc++.h>
using namespace std;
int maxAmount(int i, int j, vector<int> &arr) {

    // Base case: If i > j, no more elements are left to pick
    if (i > j)
        return 0;

    // Option 1: Take the first element arr[i], and then
  //we have two choices:
    // - Skip arr[i+1] and solve the problem for range [i+2, j]
    // - Take arr[i+1] and arr[j-1] (we solve the problem for
  //range [i+1, j-1])
    int takeFirst = arr[i] + min(maxAmount(i + 2, j, arr), 
                                 maxAmount(i + 1, j - 1, arr));

    // Option 2: Take the last element arr[j], and then we have
  //two choices:
    // - Skip arr[j-1] and solve the problem for range [i, j-2]
    // - Take arr[i+1] and arr[j-1] (we solve the problem for
  //range [i+1, j-1])
    int takeLast = arr[j] + min(maxAmount(i + 1, j - 1, arr),
                                maxAmount(i, j - 2, arr));

    return max(takeFirst, takeLast);
}

int maximumAmount(vector<int> &arr) {
	
  	int n = arr.size();
    int res = maxAmount(0, n - 1, arr);

    return res;
}

int main() {

    vector<int> arr = {5, 3, 7, 10};
    int res = maximumAmount(arr);
    cout << res << endl;

    return 0;
}
Java
// Function to calculate the maximum amount one can collect
// using the optimal strategy from index i to index j
// using recursion

import java.util.*;

class GfG { 
  
    static int maxAmount(int i, int j, int[] arr) {
      
        // Base case: If i > j, no more elements are left to
        // pick
        if (i > j)
            return 0;

        // Option 1: Take the first element arr[i], and then
        // we have two choices:
        // - Skip arr[i+1] and solve the problem for range
        // [i+2, j]
        // - Take arr[i+1] and arr[j-1] (we solve the
        // problem for range [i+1, j-1])
        int takeFirst
            = arr[i]
              + Math.min(maxAmount(i + 2, j, arr),
                         maxAmount(i + 1, j - 1, arr));

        // Option 2: Take the last element arr[j], and then
        // we have two choices:
        // - Skip arr[j-1] and solve the problem for range
        // [i, j-2]
        // - Take arr[i+1] and arr[j-1] (we solve the
        // problem for range [i+1, j-1])
        int takeLast
            = arr[j]
              + Math.min(maxAmount(i + 1, j - 1, arr),
                         maxAmount(i, j - 2, arr));
      
        return Math.max(takeFirst, takeLast);
    }

    static int maximumAmount(int[] arr) {
		
      	int n = arr.length;
        int res = maxAmount(0, n - 1, arr);

        return res;
    }

    public static void main(String[] args) {

        int[] arr = { 5, 3, 7, 10 };

        int res = maximumAmount(arr);
        System.out.println(res);
    }
}
Python
# Function to calculate the maximum amount one can collect
# using the optimal strategy from index i to index j
# using recursion


def maxAmount(i, j, arr):

    # Base case: If i > j, no more elements 
    # are left to pick
    if i > j:
        return 0

    # Option 1: Take the first element arr[i], and then we
    # have two choices:
    # - Skip arr[i+1] and solve the problem for range [i+2, j]
    # - Take arr[i+1] and arr[j-1] (we solve the problem for range [i+1, j-1])
    takeFirst = arr[i] + min(maxAmount(i + 2, j, arr),
                             maxAmount(i + 1, j - 1, arr))

    # Option 2: Take the last element arr[j], and then we 
    # have two choices:
    # - Skip arr[j-1] and solve the problem for range [i, j-2]
    # - Take arr[i+1] and arr[j-1] (we solve the problem for range [i+1, j-1])
    takeLast = arr[j] + min(maxAmount(i + 1, j - 1, arr),
                            maxAmount(i, j - 2, arr))

    return max(takeFirst, takeLast)


def maximumAmount(arr):
	
    n = len(arr)
    res = maxAmount(0, n - 1, arr)
    return res


if __name__ == "__main__":

    arr = [5, 3, 7, 10]
    res = maximumAmount(arr)
    print(res)
C#
// Function to calculate the maximum amount one can collect
// using the optimal strategy from index i to index j
// using recursion
using System;
using System.Collections.Generic;
class GfG {

    static int MaxAmount(int i, int j, int[] arr) {
      
        // Base case: If i > j, no more elements are left to
        // pick
        if (i > j)
            return 0;

        // Option 1: Take the first element arr[i], and then
        // we have two choices:
        // - Skip arr[i+1] and solve the problem for range
        // [i+2, j]
        // - Take arr[i+1] and arr[j-1] (we solve the
        // problem for range [i+1, j-1])
        int takeFirst
            = arr[i]
              + Math.Min(MaxAmount(i + 2, j, arr),
                         MaxAmount(i + 1, j - 1, arr));

        // Option 2: Take the last element arr[j], and then
        // we have two choices:
        // - Skip arr[j-1] and solve the problem for range
        // [i, j-2]
        // - Take arr[i+1] and arr[j-1] (we solve the
        // problem for range [i+1, j-1])
        int takeLast
            = arr[j]
              + Math.Min(MaxAmount(i + 1, j - 1, arr),
                         MaxAmount(i, j - 2, arr));

        // return  the maximum of the two choices
        return Math.Max(takeFirst, takeLast);
    }

    static int MaximumAmount(int[] arr) {
      
      	int n = arr.Length;
        int res = MaxAmount(0, n - 1, arr);
        return res;
    }

    static void Main() {

        int[] arr = { 5, 3, 7, 10 };
        int res = MaximumAmount(arr);
        Console.WriteLine(res);
    }
}
JavaScript
// Function to calculate the maximum amount one can collect
// using the optimal strategy from index i to index j
// using recursion
function maxAmount(i, j, arr) {

    // Base case: If i > j, no more elements are left to
    // pick
    if (i > j)
        return 0;

    // Option 1: Take the first element arr[i], and then we
    // have two choices:
    // - Skip arr[i+1] and solve the problem for range [i+2,
    // j]
    // - Take arr[i+1] and arr[j-1] (we solve the problem
    // for range [i+1, j-1])
    const takeFirst
        = arr[i]
          + Math.min(maxAmount(i + 2, j, arr),
                     maxAmount(i + 1, j - 1, arr));

    // Option 2: Take the last element arr[j], and then we
    // have two choices:
    // - Skip arr[j-1] and solve the problem for range [i,
    // j-2]
    // - Take arr[i+1] and arr[j-1] (we solve the problem
    // for range [i+1, j-1])
    const takeLast
        = arr[j]
          + Math.min(maxAmount(i + 1, j - 1, arr),
                     maxAmount(i, j - 2, arr));

    //  return  the maximum of the two choices
    return Math.max(takeFirst, takeLast);
}

function maximumAmount(arr) {
	
    let n = arr.length;
    const res = maxAmount(0, n - 1, arr);
    return res;
}

const arr = [ 5, 3, 7, 10 ];

const res = maximumAmount(arr);
console.log(res);

Output
15

Using Top-Down DP (Memoization) – O(n*n) Time and O(n*n) Space

If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming.

1. Optimal Substructure:

To solve the coin game optimally, for any range of coins from i to j, the player has two options: choose either the first or last coin. For each choice, the opponent will respond optimally, leading to the recursive relation:

  • maxAmount(i, j) = max(Vi + min( maxAmount(i+2, j), maxAmount(i+1, j-1) ), 
    Vj + min( maxAmount(i+1, j-1), maxAmount(i, j-2)))

where maxAmount(i, j) represents the maximum value the user can collect from i'th coin to j'th coin.

Base Cases

  • if j == i
    maxAmount(i, j) = Vi        
  • if j == i + 1
    maxAmount(i, j) = max(Vi , Vj)  

2. Overlapping Subproblems:

In the recursive solution, the same subproblems are recalculated many times. For instance, when calculating maxAmount(0,n-1), smaller subproblem like maxAmount(1,3) or maxAmount(2,3) get computed repeatedly as both choices for i and j in the larger subproblems depend on these smaller ranges.

C++
// C++ program to calculate the maximum amount one can collect
// using the optimal strategy from index i to index j
// using  memoziation

#include <bits/stdc++.h>
using namespace std;
int maxAmount(int i, int j, vector<int> &arr, 
              vector<vector<int>> &memo) {

    // Base case: If i > j, no more elements
    // are left to pick
    if (i > j)
        return 0;

    // If the result is already computed, return
    // from the dp table
    if (memo[i][j] != -1)
        return memo[i][j];

    // Option 1: Take the first element arr[i], and
    // then we have two choices:
    // - Skip arr[i+1] and solve the problem for
    // range [i+2, j]
    // - Take arr[i+1] and arr[j-1] (we solve the
    // problem for range [i+1, j-1])
    int takeFirst = arr[i] + min(maxAmount(i + 2, j, arr, memo), 
                                 maxAmount(i + 1, j - 1, arr, memo));

    // Option 2: Take the last element arr[j], and then we have
    // two choices:
    // - Skip arr[j-1] and solve the problem for range [i, j-2]
    // - Take arr[i+1] and arr[j-1] (we solve the problem for range
    //[i+1, j-1])
    int takeLast = arr[j] + min(maxAmount(i + 1, j - 1, arr, memo),
                                maxAmount(i, j - 2, arr, memo));

    // Store the maximum of the two choices
    return memo[i][j] = max(takeFirst, takeLast);
}

int maximumAmount(vector<int> &arr) {
  
  	int n = arr.size();

    // Create a 2D DP table initialized to -1
  	// (indicating uncalculated states)
    vector<vector<int>> memo(n, vector<int>(n, -1));

    int res = maxAmount(0, n - 1, arr, memo);

    return res;
}

int main() {
  
    vector<int> arr = {5, 3, 7, 10};
    int res = maximumAmount(arr);
    cout << res << endl;

    return 0;
}
Java
// Java program to calculate the maximum amount one can collect
// using the optimal strategy from index i to index j
// using memoziation

import java.util.*;
class GfG {
    static int maxAmount(int i, int j, int[] arr,
                         int[][] memo) {

        // Base case: If i > j, no more elements are left to
        // pick
        if (i > j)
            return 0;

        // If the result is already computed, return it from
        // the dp table
        if (memo[i][j] != -1)
            return memo[i][j];

        // Option 1: Take the first element arr[i], and then
        // we have two choices:
        // - Skip arr[i+1] and solve the problem for range
        // [i+2, j]
        // - Take arr[i+1] and arr[j-1] (we solve the
        // problem for range [i+1, j-1])
        int takeFirst
            = arr[i]
              + Math.min(maxAmount(i + 2, j, arr, memo),
                         maxAmount(i + 1, j - 1, arr, memo));

        // Option 2: Take the last element arr[j], and then
        // we have two choices:
        // - Skip arr[j-1] and solve the problem for range
        // [i, j-2]
        // - Take arr[i+1] and arr[j-1] (we solve the
        // problem for range [i+1, j-1])
        int takeLast
            = arr[j]
              + Math.min(maxAmount(i + 1, j - 1, arr,memo),
                         maxAmount(i, j - 2, arr, memo));

        // Store the maximum of the two choices
        return memo[i][j] = Math.max(takeFirst, takeLast);
    }

    static int maximumAmount(int[] arr) {
		
      
      	int n = arr.length;
      
        // Create a 2D DP table initialized to -1
        // (indicating uncalculated states)
        int[][] memo = new int[n][n];
        for (int[] row : memo) {
            Arrays.fill(row, -1);
        }

        int res = maxAmount(0, n - 1, arr, memo);

        return res;
    }

    public static void main(String[] args) {

        int[] arr = { 5, 3, 7, 10 };
        int res = maximumAmount(arr);
        System.out.println(res);
    }
}
Python
#  Python program to calculate the maximum amount one can collect
# using the optimal strategy from index i to index j
# using memoziation


def maxAmount(i, j, arr, memo):

    # Base case: If i > j, no more elements are
    # left to pick
    if i > j:
        return 0

    # If the result is already computed, return it
    # from the dp table
    if memo[i][j] != -1:
        return memo[i][j]

    # Option 1: Take the first element arr[i], and then we have
    # two choices:
    # - Skip arr[i+1] and solve the problem for range [i+2, j]
    # - Take arr[i+1] and arr[j-1] (we solve the problem for
    # range [i+1, j-1])
    takeFirst = arr[i] + min(maxAmount(i + 2, j, arr, memo),
                             maxAmount(i + 1, j - 1, arr, memo))

    # Option 2: Take the last element arr[j], and then we have
    # two choices:
    # - Skip arr[j-1] and solve the problem for range [i, j-2]
    # - Take arr[i+1] and arr[j-1] (we solve the problem for
    # range [i+1, j-1])
    takeLast = arr[j] + min(maxAmount(i + 1, j - 1, arr, memo),
                            maxAmount(i, j - 2, arr, memo))

    # Store the maximum of the two choices
    memo[i][j] = max(takeFirst, takeLast)

    return memo[i][j]


def maximumAmount(arr):

    n = len(arr)
    memo = [[-1] * n for _ in range(n)]
    res = maxAmount(0, n - 1, arr, memo)
    return res


if __name__ == "__main__":

    arr = [5, 3, 7, 10]
    res = maximumAmount(arr)
    print(res)
C#
// C# program to calculate the maximum amount one can collect
// using the optimal strategy from index i to index j
// using memoziation
using System;
using System.Collections.Generic;

class GfG {

    static int MaxAmount(int i, int j, int[] arr,
                         int[, ] memo) {
      
        // Base case: If i > j, no more elements are left to
        // pick
        if (i > j)
            return 0;

        // If the result is already computed, return it from
        // the dp table
        if (memo[i, j] != -1)
            return memo[i, j];

        // Option 1: Take the first element arr[i], and then
        // we have two choices:
        // - Skip arr[i+1] and solve the problem for range
        // [i+2, j]
        // - Take arr[i+1] and arr[j-1] (we solve the
        // problem for range [i+1, j-1])
        int takeFirst
            = arr[i]
              + Math.Min(MaxAmount(i + 2, j, arr,memo),
                         MaxAmount(i + 1, j - 1, arr, memo));

        // Option 2: Take the last element arr[j], and then
        // we have two choices:
        // - Skip arr[j-1] and solve the problem for range
        // [i, j-2]
        // - Take arr[i+1] and arr[j-1] (we solve the
        // problem for range [i+1, j-1])
        int takeLast
            = arr[j]
              + Math.Min(MaxAmount(i + 1, j - 1, arr, memo),
                         MaxAmount(i, j - 2, arr, memo));

        // Store the maximum of the two choices
        memo[i, j] = Math.Max(takeFirst, takeLast);

        return memo[i, j];
    }

    static int MaximumAmount(int[] arr) {
      
      	int n = arr.Length;
      
        // Create a 2D DP table initialized to -1
        // (indicating uncalculated states)
        int[, ] memo = new int[n, n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                memo[i, j] = -1;
            }
        }

        int res = MaxAmount(0, n - 1, arr, memo);

        return res;
    }

    static void Main() {
      
        int[] arr = { 5, 3, 7, 10 };
        int res = MaximumAmount(arr);

        Console.WriteLine(res);
    }
}
JavaScript
// JavaScript program to calculate the maximum amount one can collect
// using the optimal strategy from index i to index j
// using memoziation

function maxAmount(i, j, arr, memo) {

    // Base case: If i > j, no more elements are left to
    // pick
    if (i > j)
        return 0;

    // If the result is already computed, return it from the
    // dp table
    if (memo[i][j] !== -1)
        return memo[i][j];

    // Option 1: Take the first element arr[i], and then we
    // have two choices:
    // - Skip arr[i+1] and solve the problem for range [i+2,
    // j]
    // - Take arr[i+1] and arr[j-1] (we solve the problem
    // for range [i+1, j-1])
    const takeFirst
        = arr[i]
          + Math.min(maxAmount(i + 2, j, arr, memo),
                     maxAmount(i + 1, j - 1, arr, memo));

    // Option 2: Take the last element arr[j], and then we
    // have two choices:
    // - Skip arr[j-1] and solve the problem for range [i,
    // j-2]
    // - Take arr[i+1] and arr[j-1] (we solve the problem
    // for range [i+1, j-1])
    const takeLast
        = arr[j]
          + Math.min(maxAmount(i + 1, j - 1, arr, memo),
                     maxAmount(i, j - 2, arr, memo));

    // Store the maximum of the two choices
    memo[i][j] = Math.max(takeFirst, takeLast);

    return memo[i][j];
}

function maximumAmount(arr) {

	let n = arr.length;

    // Create a 2D DP table initialized to -1 (indicating
    // uncalculated states)
    const memo
        = Array.from({length : n}, () => Array(n).fill(-1));

    const res = maxAmount(0, n - 1, arr, memo);

    return res;
}

const arr = [ 5, 3, 7, 10 ];

const res = maximumAmount(arr);
console.log(res);

Output
15

Using Bottom-Up DP (Tabulation) â€“ O(n*n) Time and O(n*n) Space

In this problem, two players alternately pick coins from either end of a row of coins. Both players play optimally, aiming to maximize their own collected sum. To solve this optimally, we consider each choice a player could make and account for the opponent’s best possible counter-move. The solution then uses dynamic programming to store intermediate results in a table, avoiding redundant calculations.

The recurrence relation for dp[i][j], the maximum coins the first player can collect from arr[i] to arr[j], is:

  • dp[i][j] = max(arr[i] + min(dp[i+2][j], dp[i+1][j-1]), arr[j] + min(dp[i+1][j-1], dp[i][j-2]))

where:

  • Choosing arr[i] leaves the opponent to choose from dp[i+2][j] or dp[i+1][j-1].
  • Choosing arr[j] leaves the opponent to choose from dp[i+1][j-1] or dp[i][j-2].

Base Cases:

  • If i == j, there's only one coin left, so dp[i][j] = arr[i].
  • If i > j, no coins remain, so dp[i][j] = 0.
C++
// C++ program to find out
// maximum value from a given
// sequence of coins using Tabulation
#include <bits/stdc++.h>
using namespace std;

int maximumAmount(vector<int> &arr) {
	
  	int n = arr.size();
  
    // Create a table to store
    // solutions of subproblems
    int dp[n][n];

    // Fill table using above
    // recursive formula. Note
    // that the table is filled
    // in diagonal fashion,
    // from diagonal elements to
    // table[0][n-1] which is the result.
    for (int gap = 0; gap < n; ++gap) {
        for (int i = 0, j = gap; j < n; ++i, ++j) {

            // Here x is value of F(i+2, j),
            // y is F(i+1, j-1) and
            // z is F(i, j-2) in above recursive
            // formula
            int x = ((i + 2) <= j) ? dp[i + 2][j] : 0;
            int y = ((i + 1) <= (j - 1)) ? dp[i + 1][j - 1] : 0;
            int z = (i <= (j - 2)) ? dp[i][j - 2] : 0;

            dp[i][j] = max(arr[i] + min(x, y), arr[j] + min(y, z));
        }
    }

    return dp[0][n - 1];
}

int main() {

    vector<int> arr = {5, 3, 7, 10};
    int res = maximumAmount(arr);
    cout << res;
    return 0;
}
Java
// Java program to find out maximum
// value from a given sequence of coins
// using Tabulation
import java.io.*;

class GfG {
    static int maximumAmount(int arr[]) {
		
      	int n = arr.length;
      
        // Create a table to store
        // solutions of subproblems
        int dp[][] = new int[n][n];
        int gap, i, j, x, y, z;

        // Fill table using above recursive formula.
        // Note that the tableis filled in diagonal
        // fashion,
        // from diagonal elements to table[0][n-1]
        // which is the result.
        for (gap = 0; gap < n; ++gap) {
            for (i = 0, j = gap; j < n; ++i, ++j) {

                // Here x is value of F(i+2, j),
                // y is F(i+1, j-1) and z is
                // F(i, j-2) in above recursive formula
                x = ((i + 2) <= j) ? dp[i + 2][j] : 0;
                y = ((i + 1) <= (j - 1))
                        ? dp[i + 1][j - 1]
                        : 0;
                z = (i <= (j - 2)) ? dp[i][j - 2] : 0;

                dp[i][j]
                    = Math.max(arr[i] + Math.min(x, y),
                               arr[j] + Math.min(y, z));
            }
        }
        return dp[0][n - 1];
    }

    public static void main(String[] args) {
      
        int arr[] = {5, 3, 7, 10};
        int res = maximumAmount(arr);
        System.out.print(res);
    }
}
Python
# Python program to find out maximum
# value from a given sequence of coins
# using tabulation

def maximumAmount(arr):
    n = len(arr)

    # Create a table to store solutions of subproblems
    dp = [[0 for _ in range(n)] for _ in range(n)]

    # Fill table using above recursive formula.
    # Note that the table is filled in diagonal fashion
    # from diagonal elements to table[0][n-1] which is the result.
    for gap in range(n):
        for j in range(gap, n):
            i = j - gap

            # Here x is value of F(i + 2, j),
            # y is F(i + 1, j-1) and z is F(i, j-2) in above
            # recursive formula
            x = 0
            if (i + 2) <= j:
                x = dp[i + 2][j]
            y = 0
            if (i + 1) <= (j - 1):
                y = dp[i + 1][j - 1]
            z = 0
            if i <= (j - 2):
                z = dp[i][j - 2]

            dp[i][j] = max(arr[i] + min(x, y), arr[j] + min(y, z))

    return dp[0][n - 1]


arr = [5, 3, 7, 10]
print(maximumAmount(arr))
C#
// C# program to find out
// maximum value from a given
// sequence of coins using Tabulation
using System;

class GfG {

    static int maximumAmount(int[] arr) {
			
      	int n = arr.Length;
      
        // Create a table to store solutions of subproblems
        int[, ] dp = new int[n, n];
        int gap, i, j, x, y, z;

        // Fill table using above recursive formula.
        // Note that the tableis filled in diagonal
        // fashion,
        // from diagonal elements to table[0][n-1]
        // which is the result.
        for (gap = 0; gap < n; ++gap) {
            for (i = 0, j = gap; j < n; ++i, ++j) {

                // Here x is value of F(i+2, j),
                // y is F(i+1, j-1) and z is
                // F(i, j-2) in above recursive formula
                x = ((i + 2) <= j) ? dp[i + 2, j] : 0;
                y = ((i + 1) <= (j - 1))
                        ? dp[i + 1, j - 1]
                        : 0;
                z = (i <= (j - 2)) ? dp[i, j - 2] : 0;

                dp[i, j]
                    = Math.Max(arr[i] + Math.Min(x, y),
                               arr[j] + Math.Min(y, z));
            }
        }

        return dp[0, n - 1];
    }

    static public void Main() {
      
        int[] arr = {5, 3, 7, 10};
        Console.WriteLine(maximumAmount(arr));
    }
}
JavaScript
// Returns optimal value possible
// that a player can collect from
// an array of coins of size n.
// Note than n must be even
function maximumAmount(arr) {
	
    let n = arr.length;
    
    // Create a table to store
    // solutions of subproblems
    let dp = new Array(n);
    let gap, i, j, x, y, z;

    for (let d = 0; d < n; d++) {
        dp[d] = new Array(n);
    }

    // Fill table using above recursive formula.
    // Note that the tableis filled in diagonal
    // fashion,
    // from diagonal elements to table[0][n-1]
    // which is the result.
    for (gap = 0; gap < n; ++gap) {
        for (i = 0, j = gap; j < n; ++i, ++j) {
            
            // Here x is value of F(i+2, j),
            // y is F(i+1, j-1) and z is
            // F(i, j-2) in above recursive formula
            x = ((i + 2) <= j) ? dp[i + 2][j] : 0;
            y = ((i + 1) <= (j - 1)) ? dp[i + 1][j - 1]
                                     : 0;
            z = (i <= (j - 2)) ? dp[i][j - 2] : 0;

            dp[i][j] = Math.max(arr[i] + Math.min(x, y),
                                   arr[j] + Math.min(y, z));
        }
    }
    return dp[0][n - 1];
}

let arr = [5, 3, 7, 10];
console.log(maximumAmount(arr));

Output
15

Note: The above solution can be optimized by using less number of comparisons for every choice. Please refer below.

 Efficient approach : Space optimization - O(n^2) Time and O(n) Space

In previous approach the current value dp[i][j] is only depend upon the current and previous row values of DP. So to optimize the space complexity we use a single 1D array to store the computations.


We are solving a problem that involves partitioning or selecting subsets in such a way that the total sum can be split or balanced. The reason the formula (sum + dp[n – 1]) / 2 works is that dp[n – 1] represents the cumulative number of valid ways or values computed up to the last index, and by adding the total sum, we’re essentially accounting for the symmetrical nature of subset combinations. Dividing by 2 removes the double counting due to symmetric pairs (i.e., choosing set A vs. set B in a split).

Implementation steps:

  • Create a 1D vector dp of size n to store subproblem results.
  • Initialize base case in dp with appropriate starting values.
  • Use a nested loop to iterate through the problem space.
  • In each iteration, update dp values using previous computations.
  • After processing, return the result using (sum + dp[n - 1]) / 2.
C++
#include <bits/stdc++.h>
using namespace std;

// Function to find the maximum possible
// amount of money we can win.
int maximumAmount(vector<int> arr) {

    int n = arr.size();
    int sum = 0;
    vector<int> dp(n, 0);

    for (int i = (n - 1); i >= 0; i--) {
        // Calculating the sum of all the elements
        sum += arr[i];

        for (int j = i; j < n; j++) {
            if (i == j) {
                // If there is only one element
                dp[j] = arr[j];
            } else {
                // Calculating the dp states using the relation
                dp[j] = max(arr[i] - dp[j], arr[j] - dp[j - 1]);
            }
        }
    }

    // Return the final result
    return (sum + dp[n - 1]) / 2;
}

// Driver Code
int main() {

    vector<int> arr1 = {5, 3, 7, 10};
    printf("%d\n", maximumAmount(arr1));

    return 0;
}
Java
import java.util.*;

class GfG {
    // Function to find the maximum possible amount of money we can win.
    static int maximumAmount(int[] arr) {
        
        int n = arr.length;
        int sum = 0;
        int[] dp = new int[n];
        Arrays.fill(dp, 0);

        for (int i = (n - 1); i >= 0; i--) {
            // Calculating the sum of all the elements
            sum += arr[i];

            for (int j = i; j < n; j++) {
                if (i == j) {
                    // If there is only one element, take it
                    dp[j] = arr[j];
                } else {
                    // Dynamic programming transition
                    dp[j] = Math.max(arr[i] - dp[j], arr[j] - dp[j - 1]);
                }
            }
        }

        // Return final result
        return (sum + dp[n - 1]) / 2;
    }

    // Driver Code
    public static void main(String[] args) {
        int[] arr1 = {5, 3, 7, 10};
        System.out.println(maximumAmount(arr1));
    }
}
Python
def maximumAmount(arr):
	n = len(arr)
	sum = 0
	dp = [0] * n
	for i in range(n - 1, -1, -1):
	
		# Calculating the sum of all the elements
		sum += arr[i]
		for j in range(i, n):
			if i == j:
			
				# If there is only one element then we
				# can only get arr[i] score
				dp[j] = arr[j]
			else:
			
				# Calculating the dp states
				# using the relation
				dp[j] = max(arr[i] - dp[j], arr[j] - dp[j - 1])
				
	# Equating and returning the final answer
	# as per the relation
	return (sum + dp[n - 1]) // 2


if __name__ == "__main__":
    arr1 = [5, 3, 7, 10]
    print(maximumAmount(arr1))
C#
using System;

class GfG{
    // Function to find the maximum possible amount of money we can win.
    static int maximumAmount(int[] arr){
        int n = arr.Length;
        int sum = 0;
        int[] dp = new int[n];

        for (int i = n - 1; i >= 0; i--){
            
            // Calculating the sum of all the elements
            sum += arr[i];

            for (int j = i; j < n; j++){
                
                if (i == j){
                    
                    // If there is only one element, we can only take arr[i]
                    dp[j] = arr[j];
                }
                else{
                    
                    // Calculating the dp states using the relation
                    dp[j] = Math.Max(arr[i] - dp[j], arr[j] - dp[j - 1]);
                }
            }
        }

        // Returning the final answer as per the relation
        return (sum + dp[n - 1]) / 2;
    }

    // Driver Code
    static void Main(){
        
        int[] arr1 = {5, 3, 7, 10};
        Console.WriteLine(maximumAmount(arr1));
    }
}
JavaScript
// Function to find the maximum possible
// amount of money we can win.
function maximumAmount(arr){
    
    let n = arr.length;  // Calculate n inside the function
    let sum = 0;
    let dp = new Array(n).fill(0);
    
    for (let i = (n - 1); i >= 0; i--) {

        // Calculating the sum of all the elements
        sum += arr[i];
        
        for (let j = i; j < n; j++) {
            if (i == j) {

                // If there is only one element then we
                // can only get arr[i] score
                dp[j] = arr[j];
            }
            else {
                // Calculating the dp states
                // using the relation
                dp[j] = Math.max(arr[i] - dp[j],
                             arr[j] - dp[j - 1]);
            }
        }
    }
    // Equating and returning the final answer
    // as per the relation
    return Math.floor(sum + dp[n - 1]) / 2;
}

// Driver Code
let arr1 = [5, 3, 7, 10];
console.log(maximumAmount(arr1));  // Now you don't need to pass 'n'

Output
15



Next Article

Similar Reads