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.
The user chooses the 'ith' coin with value 'Vi': The opponent either chooses (i+1)th coin or jthcoin. 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 jthcoin and [i+1, j-1] is the range of indices available to the user if the opponent picks up the ithcoin.
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>usingnamespacestd;intmaxAmount(inti,intj,vector<int>&arr){// Base case: If i > j, no more elements are left to pickif(i>j)return0;// 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])inttakeFirst=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])inttakeLast=arr[j]+min(maxAmount(i+1,j-1,arr),maxAmount(i,j-2,arr));returnmax(takeFirst,takeLast);}intmaximumAmount(vector<int>&arr){intn=arr.size();intres=maxAmount(0,n-1,arr);returnres;}intmain(){vector<int>arr={5,3,7,10};intres=maximumAmount(arr);cout<<res<<endl;return0;}
Java
// Function to calculate the maximum amount one can collect// using the optimal strategy from index i to index j// using recursionimportjava.util.*;classGfG{staticintmaxAmount(inti,intj,int[]arr){// Base case: If i > j, no more elements are left to// pickif(i>j)return0;// 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])inttakeFirst=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])inttakeLast=arr[j]+Math.min(maxAmount(i+1,j-1,arr),maxAmount(i,j-2,arr));returnMath.max(takeFirst,takeLast);}staticintmaximumAmount(int[]arr){intn=arr.length;intres=maxAmount(0,n-1,arr);returnres;}publicstaticvoidmain(String[]args){int[]arr={5,3,7,10};intres=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 recursiondefmaxAmount(i,j,arr):# Base case: If i > j, no more elements # are left to pickifi>j:return0# 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))returnmax(takeFirst,takeLast)defmaximumAmount(arr):n=len(arr)res=maxAmount(0,n-1,arr)returnresif__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 recursionusingSystem;usingSystem.Collections.Generic;classGfG{staticintMaxAmount(inti,intj,int[]arr){// Base case: If i > j, no more elements are left to// pickif(i>j)return0;// 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])inttakeFirst=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])inttakeLast=arr[j]+Math.Min(MaxAmount(i+1,j-1,arr),MaxAmount(i,j-2,arr));// return the maximum of the two choicesreturnMath.Max(takeFirst,takeLast);}staticintMaximumAmount(int[]arr){intn=arr.Length;intres=MaxAmount(0,n-1,arr);returnres;}staticvoidMain(){int[]arr={5,3,7,10};intres=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 recursionfunctionmaxAmount(i,j,arr){// Base case: If i > j, no more elements are left to// pickif(i>j)return0;// 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])consttakeFirst=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])consttakeLast=arr[j]+Math.min(maxAmount(i+1,j-1,arr),maxAmount(i,j-2,arr));// return the maximum of the two choicesreturnMath.max(takeFirst,takeLast);}functionmaximumAmount(arr){letn=arr.length;constres=maxAmount(0,n-1,arr);returnres;}constarr=[5,3,7,10];constres=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:
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>usingnamespacestd;intmaxAmount(inti,intj,vector<int>&arr,vector<vector<int>>&memo){// Base case: If i > j, no more elements// are left to pickif(i>j)return0;// If the result is already computed, return// from the dp tableif(memo[i][j]!=-1)returnmemo[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])inttakeFirst=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])inttakeLast=arr[j]+min(maxAmount(i+1,j-1,arr,memo),maxAmount(i,j-2,arr,memo));// Store the maximum of the two choicesreturnmemo[i][j]=max(takeFirst,takeLast);}intmaximumAmount(vector<int>&arr){intn=arr.size();// Create a 2D DP table initialized to -1// (indicating uncalculated states)vector<vector<int>>memo(n,vector<int>(n,-1));intres=maxAmount(0,n-1,arr,memo);returnres;}intmain(){vector<int>arr={5,3,7,10};intres=maximumAmount(arr);cout<<res<<endl;return0;}
Java
// Java program to calculate the maximum amount one can collect// using the optimal strategy from index i to index j// using memoziationimportjava.util.*;classGfG{staticintmaxAmount(inti,intj,int[]arr,int[][]memo){// Base case: If i > j, no more elements are left to// pickif(i>j)return0;// If the result is already computed, return it from// the dp tableif(memo[i][j]!=-1)returnmemo[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])inttakeFirst=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])inttakeLast=arr[j]+Math.min(maxAmount(i+1,j-1,arr,memo),maxAmount(i,j-2,arr,memo));// Store the maximum of the two choicesreturnmemo[i][j]=Math.max(takeFirst,takeLast);}staticintmaximumAmount(int[]arr){intn=arr.length;// Create a 2D DP table initialized to -1// (indicating uncalculated states)int[][]memo=newint[n][n];for(int[]row:memo){Arrays.fill(row,-1);}intres=maxAmount(0,n-1,arr,memo);returnres;}publicstaticvoidmain(String[]args){int[]arr={5,3,7,10};intres=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 memoziationdefmaxAmount(i,j,arr,memo):# Base case: If i > j, no more elements are# left to pickifi>j:return0# If the result is already computed, return it# from the dp tableifmemo[i][j]!=-1:returnmemo[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 choicesmemo[i][j]=max(takeFirst,takeLast)returnmemo[i][j]defmaximumAmount(arr):n=len(arr)memo=[[-1]*nfor_inrange(n)]res=maxAmount(0,n-1,arr,memo)returnresif__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 memoziationusingSystem;usingSystem.Collections.Generic;classGfG{staticintMaxAmount(inti,intj,int[]arr,int[,]memo){// Base case: If i > j, no more elements are left to// pickif(i>j)return0;// If the result is already computed, return it from// the dp tableif(memo[i,j]!=-1)returnmemo[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])inttakeFirst=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])inttakeLast=arr[j]+Math.Min(MaxAmount(i+1,j-1,arr,memo),MaxAmount(i,j-2,arr,memo));// Store the maximum of the two choicesmemo[i,j]=Math.Max(takeFirst,takeLast);returnmemo[i,j];}staticintMaximumAmount(int[]arr){intn=arr.Length;// Create a 2D DP table initialized to -1// (indicating uncalculated states)int[,]memo=newint[n,n];for(inti=0;i<n;i++){for(intj=0;j<n;j++){memo[i,j]=-1;}}intres=MaxAmount(0,n-1,arr,memo);returnres;}staticvoidMain(){int[]arr={5,3,7,10};intres=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 memoziationfunctionmaxAmount(i,j,arr,memo){// Base case: If i > j, no more elements are left to// pickif(i>j)return0;// If the result is already computed, return it from the// dp tableif(memo[i][j]!==-1)returnmemo[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])consttakeFirst=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])consttakeLast=arr[j]+Math.min(maxAmount(i+1,j-1,arr,memo),maxAmount(i,j-2,arr,memo));// Store the maximum of the two choicesmemo[i][j]=Math.max(takeFirst,takeLast);returnmemo[i][j];}functionmaximumAmount(arr){letn=arr.length;// Create a 2D DP table initialized to -1 (indicating// uncalculated states)constmemo=Array.from({length:n},()=>Array(n).fill(-1));constres=maxAmount(0,n-1,arr,memo);returnres;}constarr=[5,3,7,10];constres=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:
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>usingnamespacestd;intmaximumAmount(vector<int>&arr){intn=arr.size();// Create a table to store// solutions of subproblemsintdp[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(intgap=0;gap<n;++gap){for(inti=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// formulaintx=((i+2)<=j)?dp[i+2][j]:0;inty=((i+1)<=(j-1))?dp[i+1][j-1]:0;intz=(i<=(j-2))?dp[i][j-2]:0;dp[i][j]=max(arr[i]+min(x,y),arr[j]+min(y,z));}}returndp[0][n-1];}intmain(){vector<int>arr={5,3,7,10};intres=maximumAmount(arr);cout<<res;return0;}
Java
// Java program to find out maximum// value from a given sequence of coins// using Tabulationimportjava.io.*;classGfG{staticintmaximumAmount(intarr[]){intn=arr.length;// Create a table to store// solutions of subproblemsintdp[][]=newint[n][n];intgap,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 formulax=((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));}}returndp[0][n-1];}publicstaticvoidmain(String[]args){intarr[]={5,3,7,10};intres=maximumAmount(arr);System.out.print(res);}}
Python
# Python program to find out maximum# value from a given sequence of coins# using tabulationdefmaximumAmount(arr):n=len(arr)# Create a table to store solutions of subproblemsdp=[[0for_inrange(n)]for_inrange(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.forgapinrange(n):forjinrange(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 formulax=0if(i+2)<=j:x=dp[i+2][j]y=0if(i+1)<=(j-1):y=dp[i+1][j-1]z=0ifi<=(j-2):z=dp[i][j-2]dp[i][j]=max(arr[i]+min(x,y),arr[j]+min(y,z))returndp[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 TabulationusingSystem;classGfG{staticintmaximumAmount(int[]arr){intn=arr.Length;// Create a table to store solutions of subproblemsint[,]dp=newint[n,n];intgap,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 formulax=((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));}}returndp[0,n-1];}staticpublicvoidMain(){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 evenfunctionmaximumAmount(arr){letn=arr.length;// Create a table to store// solutions of subproblemsletdp=newArray(n);letgap,i,j,x,y,z;for(letd=0;d<n;d++){dp[d]=newArray(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 formulax=((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));}}returndp[0][n-1];}letarr=[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>usingnamespacestd;// Function to find the maximum possible// amount of money we can win.intmaximumAmount(vector<int>arr){intn=arr.size();intsum=0;vector<int>dp(n,0);for(inti=(n-1);i>=0;i--){// Calculating the sum of all the elementssum+=arr[i];for(intj=i;j<n;j++){if(i==j){// If there is only one elementdp[j]=arr[j];}else{// Calculating the dp states using the relationdp[j]=max(arr[i]-dp[j],arr[j]-dp[j-1]);}}}// Return the final resultreturn(sum+dp[n-1])/2;}// Driver Codeintmain(){vector<int>arr1={5,3,7,10};printf("%d\n",maximumAmount(arr1));return0;}
Java
importjava.util.*;classGfG{// Function to find the maximum possible amount of money we can win.staticintmaximumAmount(int[]arr){intn=arr.length;intsum=0;int[]dp=newint[n];Arrays.fill(dp,0);for(inti=(n-1);i>=0;i--){// Calculating the sum of all the elementssum+=arr[i];for(intj=i;j<n;j++){if(i==j){// If there is only one element, take itdp[j]=arr[j];}else{// Dynamic programming transitiondp[j]=Math.max(arr[i]-dp[j],arr[j]-dp[j-1]);}}}// Return final resultreturn(sum+dp[n-1])/2;}// Driver Codepublicstaticvoidmain(String[]args){int[]arr1={5,3,7,10};System.out.println(maximumAmount(arr1));}}
Python
defmaximumAmount(arr):n=len(arr)sum=0dp=[0]*nforiinrange(n-1,-1,-1):# Calculating the sum of all the elementssum+=arr[i]forjinrange(i,n):ifi==j:# If there is only one element then we# can only get arr[i] scoredp[j]=arr[j]else:# Calculating the dp states# using the relationdp[j]=max(arr[i]-dp[j],arr[j]-dp[j-1])# Equating and returning the final answer# as per the relationreturn(sum+dp[n-1])//2if__name__=="__main__":arr1=[5,3,7,10]print(maximumAmount(arr1))
C#
usingSystem;classGfG{// Function to find the maximum possible amount of money we can win.staticintmaximumAmount(int[]arr){intn=arr.Length;intsum=0;int[]dp=newint[n];for(inti=n-1;i>=0;i--){// Calculating the sum of all the elementssum+=arr[i];for(intj=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 relationdp[j]=Math.Max(arr[i]-dp[j],arr[j]-dp[j-1]);}}}// Returning the final answer as per the relationreturn(sum+dp[n-1])/2;}// Driver CodestaticvoidMain(){int[]arr1={5,3,7,10};Console.WriteLine(maximumAmount(arr1));}}
JavaScript
// Function to find the maximum possible// amount of money we can win.functionmaximumAmount(arr){letn=arr.length;// Calculate n inside the functionletsum=0;letdp=newArray(n).fill(0);for(leti=(n-1);i>=0;i--){// Calculating the sum of all the elementssum+=arr[i];for(letj=i;j<n;j++){if(i==j){// If there is only one element then we// can only get arr[i] scoredp[j]=arr[j];}else{// Calculating the dp states// using the relationdp[j]=Math.max(arr[i]-dp[j],arr[j]-dp[j-1]);}}}// Equating and returning the final answer// as per the relationreturnMath.floor(sum+dp[n-1])/2;}// Driver Codeletarr1=[5,3,7,10];console.log(maximumAmount(arr1));// Now you don't need to pass 'n'
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.