Maximize Sum possible from an Array by the given moves | Function to find the maximum sum possible by given moves from the array ; Checking for boundary ; If previously computed subproblem occurs ; If element can be moved left ; Calculate maximum possible sum by moving left from current index ; If element can be moved right ; Calculate maximum possible sum by moving right from current index and update the maximum sum ; Store the maximum sum ; Driver Code ; Function call
function maxValue ( a , n , pos , moves , left , dp ) { if ( moves == 0 || ( pos > n - 1 pos < 0 ) ) return 0 ; if ( dp [ pos ] [ left ] != - 1 ) return dp [ pos ] [ left ] ; let value = 0 ; if ( left > 0 && pos >= 1 ) value = Math . max ( value , a [ pos ] + maxValue ( a , n , pos - 1 , moves - 1 , left - 1 , dp ) ) ; if ( pos <= n - 1 ) value = Math . max ( value , a [ pos ] + maxValue ( a , n , pos + 1 , moves - 1 , left , dp ) ) ; return dp [ pos ] [ left ] = value ; } let n = 5 ; let a = [ 1 , 5 , 4 , 3 , 2 ] ; let k = 1 ; let m = 4 ; let dp = new Array ( n + 1 ) ; for ( var i = 0 ; i < dp . length ; i ++ ) { dp [ i ] = new Array ( 2 ) ; } for ( var i = 0 ; i < dp . length ; i ++ ) { for ( var j = 0 ; j < dp . length ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } document . write ( ( a [ 0 ] + maxValue ( a , n , 1 , m , k , dp ) ) ) ;