Maximize the profit by selling at | Function to find profit ; Calculating profit for each gadget ; Sort the profit array in descending order ; Variable to calculate total profit ; Check for best M profits ; Driver Code
function solve ( N , M , cp , sp ) { let profit = new Array ( N ) ; for ( let i = 0 ; i < N ; i ++ ) profit [ i ] = sp [ i ] - cp [ i ] ; profit . sort ( function ( a , b ) { return b - a ; } ) ; let sum = 0 ; for ( let i = 0 ; i < M ; i ++ ) { if ( profit [ i ] > 0 ) sum += profit [ i ] ; else break ; } return sum ; } let N = 5 , M = 3 ; let CP = [ 5 , 10 , 35 , 7 , 23 ] ; let SP = [ 11 , 10 , 0 , 9 , 19 ] ; document . write ( solve ( N , M , CP , SP ) ) ;