Problem
You are given a 2D integer array items
where items[i] = [pricei, beautyi]
denotes the price and beauty of an item respectively.
You are also given a 0-indexed integer array queries
. For each queries[j]
, you want to determine the maximum beauty of an item whose price is less than or equal to queries[j]
. If no such item exists, then the answer to this query is 0
.
Return an array answer
of the same length as queries
where answer[j]
is the answer to the jth
query.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Similar Problems
Maximum Profit in Job Scheduling Maximum Earnings From Taxi Maximum Number of Events That Can Be Attended Two Best Non-Overlapping Events
Solution
Method 1 - Sorting + Binary Search
To solve the problem, we need to efficiently determine the maximum beauty of an item whose price is less than or equal to each query price.
Here is the approach:
- Sort the Items:
- First, sort the
items
array based on the item prices in ascending order. - Track the maximum beauty encountered so far as we sort to ensure that each item price is associated with the maximum beauty up to that price.
- First, sort the
- Process the Queries:
- Sort the
queries
keeping track of their original indices to efficiently place results back in their original order. - Use a pointer to traverse through the sorted items and find the maximum beauty for each query price.
- If an item’s price is less than or equal to the query price, update the maximum beauty.
- Sort the
- Binary Search:
- For each query, use binary search (or two-pointer technique) to find the relevant items efficiently ensuring that the solution is optimized.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O((n + m) log n)
- Sorting the
items
array:O(n log n)
- Sorting the
queries
array:O(m log m)
- Processing each query using a pointer:
O(n + m)
- Overall:
O((n + m) log n)
- Sorting the
- 🧺 Space complexity:
O(n + m)
Method 2 -
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(NNNXXXNNN)
- 🧺 Space complexity:
O(NNNXXX)