Maximize profit possible by selling M products such that profit of a product is the number of products left of that supplier | Function to find the maximum profit by selling M number of products ; Initialize a Max - Heap to keep track of the maximum value ; Stores the maximum profit ; Traverse the array and push all the elements in max_heap ; Iterate a loop until M > 0 ; Decrement the value of M by 1 ; Pop the maximum element from the heap ; Update the maxProfit ; Push ( X - 1 ) to max heap ; Print the result ; Driver Code
function findMaximumProfit ( arr , M , N ) { let max_heap = [ ] ; let maxProfit = 0 ; for ( let i = 0 ; i < N ; i ++ ) max_heap . push ( arr [ i ] ) ; max_heap . sort ( function ( a , b ) { return a - b } ) ; max_heap . reverse ( ) ; while ( M > 0 ) { M -- ; let X = max_heap [ 0 ] ; max_heap . shift ( ) ; maxProfit += X ; max_heap . push ( X - 1 ) ; max_heap . sort ( function ( a , b ) { return a - b } ) ; max_heap . reverse ( ) ; } document . write ( maxProfit ) ; } let arr = [ 4 , 6 ] ; let M = 4 ; let N = arr . length ; findMaximumProfit ( arr , M , N ) ;