Program to find maximum number of package that can be bought by buyers in C++

C++Server Side ProgrammingProgramming

Suppose we have two lists sales and buyers. Each element in sales contains two values in the form [day, price] this indicates the package is available for sale only on that day for that given price. And each element in buyers in the form [payday, amount] indicates that the buyer has that amount of money to spend on payday and afterward. If each buyer can buy at most one package, and each package can be sold to only one person, find the maximum number of packages that can be bought.

So, if the input is like sales = [[0, 5], [0, 5], [0, 6], [1, 4], [1, 5], [3, 4]] buyers = [[0, 4], [0, 6],[1, 5]], then the output will be 3, as the first person can take package [1, 4]. The second person can take [0, 6]. And the last person can take the package [1, 5].

To solve this, we will follow these steps −

  • ret := 0

  • sort the array buyers based on payday, if paydays are same sort them on amount

  • define a set pq

  • sort the array sales

  • i := 0

  • for each items it in sales −

    • while (i < size of buyers and buyers[i, 0] <= it[0]), do −

      • insert buyers[i, 1] into pq

      • (increase i by 1)

    • j := index of pq to insert it[i] intp pq and make it sorted

    • if j is a valid index, then −

      • (increase ret by 1)

      • delete jth element from pq

  • return ret

Example  

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   static bool cmp(vector<int>& a, vector<int>& b) {
      return a[0] == b[0] ? a[1] > b[1] : a[0] < b[0];
   }
   int solve(vector<vector<int>>& sales, vector<vector<int>>& buyers) {
      int ret = 0;
      sort(buyers.begin(), buyers.end());
      multiset<int> pq;
      sort(sales.begin(), sales.end(), cmp);
      int i = 0;
      for (auto& it : sales) {
         while (i < buyers.size() && buyers[i][0] <= it[0]) {
            pq.insert(buyers[i][1]);
            i++;
         }
         auto j = pq.lower_bound(it[1]);
         if (j != pq.end()) {
            ret++;
            pq.erase(j);
         }
      }
      return ret;
   }
};
int solve(vector<vector<int>>& sales, vector<vector<int>>& buyers) {
   return (new Solution())->solve(sales, buyers);
}
int main(){
   vector<vector<int>> sales = {{0, 5},{0, 5},{0, 6},{1, 4},{1, 5},{3, 4}};
   vector<vector<int>> buyers = {{0, 4},{0, 6},{1, 5}};
   cout << solve(sales, buyers);
}

Input

{{0, 5},{0, 5},{0, 6},{1, 4},{1, 5},{3, 4}}, {{0, 4},{0, 6},{1, 5}}

Output

3
raja
Published on 22-Dec-2020 08:17:57
Advertisements