Maximum profit by selling N items at two markets | Function to calculate max profit ; Prefix sum array for profitA [ ] ; Suffix sum array for profitB [ ] ; If all the items are sold in market A ; Find the maximum profit when the first i items are sold in market A and the rest of the items are sold in market B for all possible values of i ; If all the items are sold in market B ; Driver code ; Function to calculate max profit
def maxProfit ( profitA , profitB , n ) : NEW_LINE INDENT preSum = [ 0 ] * n ; NEW_LINE preSum [ 0 ] = profitA [ 0 ] ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT preSum [ i ] = preSum [ i - 1 ] + profitA [ i ] ; NEW_LINE DEDENT suffSum = [ 0 ] * n ; NEW_LINE suffSum [ n - 1 ] = profitB [ n - 1 ] ; NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT suffSum [ i ] = suffSum [ i + 1 ] + profitB [ i ] ; NEW_LINE DEDENT res = preSum [ n - 1 ] ; NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT res = max ( res , preSum [ i ] + suffSum [ i + 1 ] ) ; NEW_LINE DEDENT res = max ( res , suffSum [ 0 ] ) ; NEW_LINE return res ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT profitA = [ 2 , 3 , 2 ] ; NEW_LINE profitB = [ 10 , 30 , 40 ] ; NEW_LINE n = len ( profitA ) ; NEW_LINE print ( maxProfit ( profitA , profitB , n ) ) ; NEW_LINE DEDENT