Most Beautiful Item for Each Query - 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.
Input & Output
Example 1 — Basic Case
$
Input:
items = [[1,2],[3,2],[2,4]], queries = [1,2,3]
›
Output:
[2,4,4]
💡 Note:
Query 1: Only item [1,2] is affordable, beauty = 2. Query 2: Items [1,2] and [2,4] are affordable, max beauty = 4. Query 3: All items affordable, max beauty = 4.
Example 2 — No Affordable Items
$
Input:
items = [[10,1000]], queries = [5]
›
Output:
[0]
💡 Note:
Query 5: The only item costs 10, which exceeds budget of 5, so return 0.
Example 3 — Multiple Queries
$
Input:
items = [[1,2],[1,2],[1,3],[1,4]], queries = [1,1]
›
Output:
[4,4]
💡 Note:
All items have price 1, so for budget 1, we can afford all items. Maximum beauty among all is 4.
Constraints
- 1 ≤ items.length ≤ 105
- 1 ≤ pricei, beautyi, queries[j] ≤ 109
- 1 ≤ queries.length ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input
Items with [price, beauty] and query budgets
2
Process
For each query, find items within budget and maximum beauty
3
Output
Array of maximum beauties for each query
Key Takeaway
🎯 Key Insight: Preprocess items by sorting and computing running maximum beauty to enable efficient binary search queries
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code