Maximize profit possible by selling M products such that profit of a product is the number of products left of that supplier | Java program for the above approach ; 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
import java . util . * ; class GFG { static void findMaximumProfit ( int [ ] arr , int M , int N ) { PriorityQueue < Integer > max_heap = new PriorityQueue < > ( ( a , b ) -> b - a ) ; int maxProfit = 0 ; for ( int i = 0 ; i < N ; i ++ ) max_heap . add ( arr [ i ] ) ; while ( M > 0 ) { M -- ; int X = max_heap . poll ( ) ; maxProfit += X ; max_heap . add ( X - 1 ) ; } System . out . println ( maxProfit ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 4 , 6 } ; int M = 4 ; int N = arr . length ; findMaximumProfit ( arr , M , N ) ; } }