Optimal Strategy for a Game | Set 2 | Java program to find out maximum value from a given sequence of coins ; For both of your choices , the opponent gives you total sum minus maximum of his value ; Returns optimal value possible that a player can collect from an array of coins of size n . Note than n must be even ; Compute sum of elements ; Initialize memoization table ; Driver Code
import java . util . * ; class GFG { static int MAX = 100 ; static int [ ] [ ] memo = new int [ MAX ] [ MAX ] ; static int oSRec ( int arr [ ] , int i , int j , int sum ) { if ( j == i + 1 ) return Math . max ( arr [ i ] , arr [ j ] ) ; if ( memo [ i ] [ j ] != - 1 ) return memo [ i ] [ j ] ; memo [ i ] [ j ] = Math . max ( ( sum - oSRec ( arr , i + 1 , j , sum - arr [ i ] ) ) , ( sum - oSRec ( arr , i , j - 1 , sum - arr [ j ] ) ) ) ; return memo [ i ] [ j ] ; } static int accumulate ( int [ ] arr , int start , int end ) { int sum = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) sum += arr [ i ] ; return sum ; } static int optimalStrategyOfGame ( int [ ] arr , int n ) { int sum = 0 ; sum = accumulate ( arr , 0 , n ) ; for ( int j = 0 ; j < MAX ; j ++ ) { for ( int k = 0 ; k < MAX ; k ++ ) memo [ j ] [ k ] = - 1 ; } return oSRec ( arr , 0 , n - 1 , sum ) ; } public static void main ( String [ ] args ) { int arr1 [ ] = { 8 , 15 , 3 , 7 } ; int n = arr1 . length ; System . out . printf ( "%dNEW_LINE", optimalStrategyOfGame ( arr1 , n ) ) ; int arr2 [ ] = { 2 , 2 , 2 , 2 } ; n = arr2 . length ; System . out . printf ( "%dNEW_LINE", optimalStrategyOfGame ( arr2 , n ) ) ; int arr3 [ ] = { 20 , 30 , 2 , 2 , 2 , 10 } ; n = arr3 . length ; System . out . printf ( "%dNEW_LINE", optimalStrategyOfGame ( arr3 , n ) ) ; } }