Maximum sum by picking elements from two arrays in order | Set 2 | Function to calculate maximum sum ; Maximum elements that can be chosen from array A ; Maximum elements that can be chosen from array B ; Stores the maximum sum possible ; Fill the dp [ ] for base case when all elements are selected from A [ ] ; Fill the dp [ ] for base case when all elements are selected from B [ ] ; Return the final answer ; Driver Program
def maximumSum ( A , B , length , X , Y ) : NEW_LINE INDENT l = length NEW_LINE l1 = min ( length , X ) NEW_LINE l2 = min ( length , Y ) NEW_LINE dp = [ [ 0 for i in range ( l2 + 1 ) ] for i in range ( l1 + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = 0 NEW_LINE max_sum = - 10 * 9 NEW_LINE for i in range ( 1 , l1 + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] + A [ i - 1 ] NEW_LINE max_sum = max ( max_sum , dp [ i ] [ 0 ] ) NEW_LINE DEDENT for i in range ( 1 , l2 + 1 ) : NEW_LINE INDENT dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] + B [ i - 1 ] NEW_LINE max_sum = max ( max_sum , dp [ 0 ] [ i ] ) NEW_LINE DEDENT for i in range ( 1 , l1 + 1 ) : NEW_LINE INDENT for j in range ( 1 , l2 + 1 ) : NEW_LINE INDENT if ( i + j <= l ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i - 1 ] [ j ] + A [ i + j - 1 ] , dp [ i ] [ j - 1 ] + B [ i + j - 1 ] ) NEW_LINE DEDENT max_sum = max ( dp [ i ] [ j ] , max_sum ) NEW_LINE DEDENT DEDENT return max_sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE B = [ 5 , 4 , 3 , 2 , 1 ] NEW_LINE X = 3 NEW_LINE Y = 2 NEW_LINE N = len ( A ) NEW_LINE print ( maximumSum ( A , B , N , X , Y ) ) NEW_LINE DEDENT