Maximize sum of odd | Function to find the maximum sum of array elements chosen by Player A according to the given criteria ; Store the key ; Corner Case ; Check if all the elements can be taken or not ; If the difference is less than or equal to the available chances then pick all numbers ; Find the sum of array elements over the range [ start , N ] ; If yes then return that value ; Traverse over the range [ 1 , 2 * M ] ; Sum of elements for Player A ; Even chance sum can be obtained by subtracting the odd chances sum - total and picking up the maximum from that ; Storing the value in dictionary ; Return the maximum sum of odd chances ; Driver code ; Stores the precomputed values ; Function Call
function recursiveChoosing ( arr , start , M , dp ) { let key = [ start , M ] ; if ( start >= N ) { return 0 ; } if ( N - start <= 2 * M ) { let sum = 0 ; for ( let i = start ; i < arr . length ; i ++ ) { sum = sum + arr [ i ] ; } return sum ; } let psa = 0 ; let sum = 0 ; for ( let i = start ; i < arr . length ; i ++ ) { sum = sum + arr [ i ] ; } let total = sum ; if ( dp . has ( key ) ) { return dp [ key ] ; } for ( let x = 1 ; x < 2 * M + 1 ; x ++ ) { let psb = recursiveChoosing ( arr , start + x , Math . max ( x , M ) , dp ) psa = Math . max ( psa , total - psb ) ; } dp [ key ] = psa ; return dp [ key ] ; } let arr = [ 2 , 7 , 9 , 4 , 4 ] ; let N = arr . length ; let dp = new Map ( ) ; document . write ( recursiveChoosing ( arr , 0 , 1 , dp ) )