Maximum score possible after performing given operations on an Array | Memoizing by the use of a table ; Function to calculate maximum score ; Bse case ; If the same state has already been computed ; Sum of array in range ( l , r ) ; If the operation is even - numbered the score is decremented ; Exploring all paths , and storing maximum value in DP table to avoid further repetitive recursive calls ; Function to find the max score ; Prefix sum array ; Calculating prefix_sum ; Initialising the DP table , - 1 represents the subproblem hasn 't been solved yet ; Driver code
dp = [ [ [ - 1 for x in range ( 100 ) ] for y in range ( 100 ) ] for z in range ( 100 ) ] NEW_LINE def MaximumScoreDP ( l , r , prefix_sum , num ) : NEW_LINE INDENT if ( l > r ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ l ] [ r ] [ num ] != - 1 ) : NEW_LINE INDENT return dp [ l ] [ r ] [ num ] NEW_LINE DEDENT current_sum = prefix_sum [ r ] NEW_LINE if ( l - 1 >= 0 ) : NEW_LINE INDENT current_sum -= prefix_sum [ l - 1 ] NEW_LINE DEDENT if ( num % 2 == 0 ) : NEW_LINE INDENT current_sum *= - 1 NEW_LINE DEDENT dp [ l ] [ r ] [ num ] = ( current_sum + max ( MaximumScoreDP ( l + 1 , r , prefix_sum , num + 1 ) , MaximumScoreDP ( l , r - 1 , prefix_sum , num + 1 ) ) ) NEW_LINE return dp [ l ] [ r ] [ num ] NEW_LINE DEDENT def findMaxScore ( a , n ) : NEW_LINE INDENT prefix_sum = [ 0 ] * n NEW_LINE prefix_sum [ 0 ] = a [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefix_sum [ i ] = prefix_sum [ i - 1 ] + a [ i ] NEW_LINE DEDENT global dp NEW_LINE return MaximumScoreDP ( 0 , n - 1 , prefix_sum , 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 6 NEW_LINE A = [ 1 , 2 , 3 , 4 , 2 , 6 ] NEW_LINE print ( findMaxScore ( A , n ) ) NEW_LINE DEDENT