Optimal Strategy for a Game
Last Updated :
23 Jul, 2025
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.
- 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.
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);
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);
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));
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'
Optimal Strategy For A Game
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem