Optimal Strategy for a Game | Set 3 | Calculates the maximum score possible for P1 If only the bags from beg to ed were available ; Length of the game ; Which turn is being played ; Base case i . e last turn ; if it is P1 's turn ; if P2 's turn ; Player picks money from the left end ; Player picks money from the right end ; if it is player 1 's turn then  current picked score added to  his total. choose maximum of  the two scores as P1 tries to  maximize his score. ; if player 2 ' s ▁ turn ▁ don ' t add current picked bag score to total . choose minimum of the two scores as P2 tries to minimize P1 's score. ; Input array ; Function Calling
function maxScore ( money , beg , ed ) { let totalTurns = money . length ; let turnsTillNow = beg + ( ( totalTurns - 1 ) - ed ) ; if ( beg == ed ) { if ( turnsTillNow % 2 == 0 ) return [ money [ beg ] , " " ] ; else return [ 0 , " " ] ; } let scoreOne = maxScore ( money , beg + 1 , ed ) ; let scoreTwo = maxScore ( money , beg , ed - 1 ) ; if ( turnsTillNow % 2 == 0 ) { if ( money [ beg ] + scoreOne [ 0 ] > money [ ed ] + scoreTwo [ 0 ] ) { return [ money [ beg ] + scoreOne [ 0 ] , " " + scoreOne [ 1 ] ] ; } else return [ money [ ed ] + scoreTwo [ [ 0 ] ] , " " + scoreTwo [ 1 ] ] ; } else { if ( scoreOne . first < scoreTwo . first ) return [ scoreOne [ 0 ] , " " + scoreOne [ 1 ] ] ; else return [ scoreTwo [ 0 ] , " " + scoreTwo [ 1 ] ] ; } } let ar = [ 10 , 80 , 90 , 30 ] ; let arraySize = ar . length ; let bags = ar ; let ans = maxScore ( bags , 0 , bags . length - 1 ) ; document . write ( ans [ 0 ] + " " + ans [ 1 ] + " " ) ;