![]() |
VOOZH | about |
There are N concert tickets available, each with a certain price given as array tickets[]. Then, M customers arrive, one after another. Each customer announces the maximum price they are willing to pay for a ticket given as array customer[], and after this, they will get a ticket with the nearest possible price such that it does not exceed the maximum price.
The task is to print, for each customer, the price that they will pay for their ticket. After this, the ticket cannot be purchased again. If a customer cannot get any ticket, print -1.
Examples:
Input: N = 5, tickets[] = {5, 3, 7, 8, 5}, M = 3, customer[] = {4, 8, 3}
Output:
3
8
-1
Explanation:
- The first customer is willing to pay a maximum price of 4, so he will purchase the ticket with cost = 3.
- The second customer is willing to pay a maximum price of 8, so he will purchase the ticket with cost = 8.
- The third customer is willing to pay a maximum price of 3, but there are no tickets left with cost <= 3, so he won't be able to purchase any ticket.
Input: N = 4, tickets[] = {1, 1, 1, 1}, M = 4, customer[] = {1, 1, 1, 1}
Output:
1
1
1
1
Approach: To solve the problem, follow the below idea:
The problem can be solved by using upper bound and a frequency map. We can store all the tickets price in a map along with the frequency of each ticket. Now, for every customer[i], we can find the upper bound of customer[i] in the map, this will give us the ticket which has just greater price than what the customer can pay. Since, in a map all the pairs are sorted on the basis of key values, we can get the price by moving to the pair just before the upper bound to get the required ticket price. If there is no pair before it, print -1. Otherwise, decrease the frequency of the ticket by 1.
Step-by-step algorithm:
Below is the implementation of the algorithm:
Result for each customer: 3 8 -1
Time Complexity: O(N * logN + M * logN), where N is the number of tickets and M is the number of customers.
Auxiliary Space: O(N)