# 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), 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 == b ? a > b : a < b;
}
int solve(vector<vector<int>>& sales, vector<vector<int>>& buyers) {
int ret = 0;
multiset<int> pq;
sort(sales.begin(), sales.end(), cmp);
int i = 0;
for (auto& it : sales) {
i++;
}
auto j = pq.lower_bound(it);
if (j != pq.end()) {
ret++;
pq.erase(j);
}
}
return ret;
}
};
int solve(vector<vector<int>>& sales, vector<vector<int>>& 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}};
}
{{0, 5},{0, 5},{0, 6},{1, 4},{1, 5},{3, 4}}, {{0, 4},{0, 6},{1, 5}}
3