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
function maxProfit ( profitA , profitB , n ) { let preSum = new Array ( n ) ; preSum [ 0 ] = profitA [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) { preSum [ i ] = preSum [ i - 1 ] + profitA [ i ] ; } let suffSum = new Array ( n ) ; suffSum [ n - 1 ] = profitB [ n - 1 ] ; for ( let i = n - 2 ; i >= 0 ; i -- ) { suffSum [ i ] = suffSum [ i + 1 ] + profitB [ i ] ; } let res = preSum [ n - 1 ] ; for ( let i = 1 ; i < n - 1 ; i ++ ) { res = Math . max ( res , preSum [ i ] + suffSum [ i + 1 ] ) ; } res = Math . max ( res , suffSum [ 0 ] ) ; return res ; } let profitA = [ 2 , 3 , 2 ] ; let profitB = [ 10 , 30 , 40 ] ; let n = profitA . length ; document . write ( maxProfit ( profitA , profitB , n ) ) ;