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
def maxValue ( a , n , pos , moves , left , dp ) : NEW_LINE INDENT if ( moves == 0 or ( pos > n - 1 or pos < 0 ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ pos ] [ left ] != - 1 ) : NEW_LINE INDENT return dp [ pos ] [ left ] NEW_LINE DEDENT value = 0 NEW_LINE if ( left > 0 and pos >= 1 ) : NEW_LINE INDENT value = max ( value , a [ pos ] + maxValue ( a , n , pos - 1 , moves - 1 , left - 1 , dp ) ) NEW_LINE DEDENT if ( pos <= n - 1 ) : NEW_LINE INDENT value = max ( value , a [ pos ] + maxValue ( a , n , pos + 1 , moves - 1 , left , dp ) ) NEW_LINE DEDENT dp [ pos ] [ left ] = value NEW_LINE return dp [ pos ] [ left ] NEW_LINE DEDENT n = 5 NEW_LINE a = [ 1 , 5 , 4 , 3 , 2 ] NEW_LINE k = 1 NEW_LINE m = 4 NEW_LINE dp = [ [ - 1 for x in range ( k + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE print ( a [ 0 ] + maxValue ( a , n , 1 , m , k , dp ) ) NEW_LINE