Maximize profit possible by selling M products such that profit of a product is the number of products left of that supplier

05 Aug, 2021
Given an array arr[] consisting of N positive integers, such that arr[i] represents the number of products the ith supplier has and a positive integer, M, the task is to find the maximum profit by selling M products if the profit of a particular product is the same as the number of products left of that supplier.
Examples:
Input: arr[] = {4, 6}, M = 4Output: 19Explanation:Below are the order of the product sell to gain the maximum profit:Product 1: Sell a product from the second supplier, then the array modifies to {4, 5} and the profit is 6.Product 2: Sell a product from the second supplier, then the array modifies to{4, 4} and the profit is 6 + 5 = 11.Product 3: Sell a product from the second supplier, then the array modifies to {4, 3} and the profit is 6 + 5 + 4 = 15.Product 4: Sell a product from the first supplier, then the array modifies to {3, 3} and the profit is 6 + 5 + 4 + 4 = 19.Therefore, the maximum profit that can be obtained by selling 4 products is 19.
Input: arr[] = {1, 2, 3}, M = 2Output: 5
Naive Approach: The given problem can be solved by selling the product from suppliers having the current maximum number of products left. So, the idea is to iterate a loop M times, and in each iteration find the value of the largest element in the array, and add its value to the profit and then decrementing its value in the array by 1. After the loop, print the value of the profit.
Time Complexity: O(M * N)Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by using the Max-Heap to keep track of the maximum element in the array in O(log N) time. Follow the below steps to solve the problem:
Initialize a Max-Heap using a priority queue, say Q to keep track of the maximum element present in the array.
Traverse the array arr[] and insert all the elements in heap Q.
Initialize a variable, say maxProfit as 0 to store the result maximum profit obtained.
Iterate a loop until M > 0, and perform the following steps:Decrease the value of M by 1.Store the value of the top element of the priority queue Q in a variable X and pop it from the priority queue.Add the value of X to the variable maxProfit and insert (X – 1) to the variable Q.
Decrease the value of M by 1.
Store the value of the top element of the priority queue Q in a variable X and pop it from the priority queue.
Add the value of X to the variable maxProfit and insert (X – 1) to the variable Q.
After completing the above steps, print the value of maxProfit as the result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to find the maximum profit// by selling M number of productsvoid findMaximumProfit(int arr[], int M, int N){         // Initialize a Max-Heap to keep    // track of the maximum value    priority_queue<int> max_heap;     // Stores the maximum profit    int maxProfit = 0;     // Traverse the array and push    // all the elements in max_heap    for(int i = 0; i < N; i++)        max_heap.push(arr[i]);     // Iterate a loop until M > 0    while (M > 0)    {                 // Decrement the value        // of M by 1        M--;         // Pop the maximum element        // from the heap        int X = max_heap.top();        max_heap.pop();                   // Update the maxProfit        maxProfit += X;         // Push (X - 1) to max heap        max_heap.push(X - 1);    }     // Print the result    cout<<maxProfit;} // Driver Codeint main(){    int arr[] = { 4, 6 };    int M = 4;    int N = sizeof(arr) / sizeof(arr[0]);         findMaximumProfit(arr, M, N);} // This code is contributed by bgangwar59
// Java program for the above approach import java.util.*; class GFG {     // Function to find the maximum profit    // by selling M number of products    static void findMaximumProfit(        int[] arr, int M, int N)    {         // Initialize a Max-Heap to keep        // track of the maximum value        PriorityQueue<Integer> max_heap            = new PriorityQueue<>((a, b) -> b - a);         // Stores the maximum profit        int maxProfit = 0;         // Traverse the array and push        // all the elements in max_heap        for (int i = 0; i < N; i++)            max_heap.add(arr[i]);         // Iterate a loop until M > 0        while (M > 0) {             // Decrement the value            // of M by 1            M--;             // Pop the maximum element            // from the heap            int X = max_heap.poll();             // Update the maxProfit            maxProfit += X;             // Push (X - 1) to max heap            max_heap.add(X - 1);        }         // Print the result        System.out.println(maxProfit);    }     // Driver Code    public static void main(String[] args)    {        int[] arr = { 4, 6 };        int M = 4;        int N = arr.length;        findMaximumProfit(arr, M, N);    }}
# Python3 program for the above approach # Function to find the maximum profit# by selling M number of productsdef findMaximumProfit(arr, M, N):         # Initialize a Max-Heap to keep    # track of the maximum value    max_heap = []     # Stores the maximum profit    maxProfit = 0     # Traverse the array and push    # all the elements in max_heap    for i in range(0, N):        max_heap.append(arr[i])            max_heap.sort()    max_heap.reverse()     # Iterate a loop until M > 0    while (M > 0):         # Decrement the value        # of M by 1        M -= 1         # Pop the maximum element        # from the heap        X = max_heap[0]        max_heap.pop(0)         # Update the maxProfit        maxProfit += X         # Push (X - 1) to max heap        max_heap.append(X - 1)        max_heap.sort()        max_heap.reverse()     # Print the result    print(maxProfit) # Driver codearr = [ 4, 6 ]M = 4N = len(arr)   findMaximumProfit(arr, M, N) # This code is contributed by rameshtravel07
// C# program for the above approachusing System;using System.Collections.Generic;class GFG {         // Function to find the maximum profit    // by selling M number of products    static void findMaximumProfit(int[] arr, int M, int N)    {          // Initialize a Max-Heap to keep        // track of the maximum value        List<int> max_heap = new List<int>();          // Stores the maximum profit        int maxProfit = 0;          // Traverse the array and push        // all the elements in max_heap        for(int i = 0; i < N; i++)            max_heap.Add(arr[i]);                    max_heap.Sort();        max_heap.Reverse();          // Iterate a loop until M > 0        while (M > 0)        {              // Decrement the value            // of M by 1            M--;              // Pop the maximum element            // from the heap            int X = max_heap[0];            max_heap.RemoveAt(0);              // Update the maxProfit            maxProfit += X;              // Push (X - 1) to max heap            max_heap.Add(X - 1);            max_heap.Sort();            max_heap.Reverse();        }          // Print the result        Console.Write(maxProfit);    }       static void Main() {    int[] arr = { 4, 6 };    int M = 4;    int N = arr.Length;           findMaximumProfit(arr, M, N);  }} // This code is contributed by mukesh07.
<script>    // Javascript program for the above approach         // Function to find the maximum profit    // by selling M number of products    function findMaximumProfit(arr, M, N)    {         // Initialize a Max-Heap to keep        // track of the maximum value        let max_heap = [];         // Stores the maximum profit        let maxProfit = 0;         // Traverse the array and push        // all the elements in max_heap        for(let i = 0; i < N; i++)            max_heap.push(arr[i]);                   max_heap.sort(function(a, b){return a - b});        max_heap.reverse();         // Iterate a loop until M > 0        while (M > 0)        {             // Decrement the value            // of M by 1            M--;             // Pop the maximum element            // from the heap            let X = max_heap[0];            max_heap.shift();             // Update the maxProfit            maxProfit += X;             // Push (X - 1) to max heap            max_heap.push(X - 1);            max_heap.sort(function(a, b){return a - b});            max_heap.reverse();        }         // Print the result        document.write(maxProfit);    }         let arr = [ 4, 6 ];    let M = 4;    let N = arr.length;          findMaximumProfit(arr, M, N);   // This code is contributed by divyeshrabadiya07.</script>
19
 
Time Complexity: O(M * log(N))Auxiliary Space: O(N)
bgangwar59
divyeshrabadiya07
rameshtravel07
mukesh07
Amazon-Question
interview-preparation
priority-queue
Arrays
Greedy
Heap
Mathematical
Arrays
Greedy
Mathematical
Heap
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
What is Data Structure: Types, Classifications and Applications
Next Greater Element
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Write a program to print all permutations of a given string
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3