Leetcode 2070: Most Beautiful Item for Each Query

grid47
grid47
Exploring patterns and algorithms
Apr 14, 2024 6 min read

You are given a list of items, where each item has a price and a beauty score. You are also given a list of price queries. For each query, find the maximum beauty of an item with a price less than or equal to the query price. If no such item exists, return 0.
Problem
Approach
Steps
Complexity
Input: You are given an array `items` where each item is represented as [price, beauty]. You are also given an array `queries` where each query is a price. For each query, find the maximum beauty of items with price <= query.
Example: Input: items = [[3, 5], [5, 7], [2, 8], [8, 2]], queries = [3, 5, 7, 9]
Constraints:
• 1 <= items.length, queries.length <= 10^5
• items[i].length == 2
• 1 <= price[i], beauty[i], queries[j] <= 10^9
Output: Return an array where each element is the maximum beauty for each query.
Example: Output: [8, 7, 7, 7]
Constraints:
• The length of the output should be the same as the length of the queries.
Goal: For each query, find the maximum beauty of an item whose price is less than or equal to the queried price.
Steps:
• 1. Sort the items based on their price.
• 2. For each query, iterate through the sorted items and track the maximum beauty of items with a price <= query.
Goal: Ensure that your solution handles the constraints effectively.
Steps:
• 1 <= items.length, queries.length <= 10^5
• 1 <= price[i], beauty[i], queries[j] <= 10^9
Assumptions:
• The price and beauty of each item is non-negative.
• Queries can have repeated prices.
Input: Input: items = [[3, 5], [5, 7], [2, 8], [8, 2]], queries = [3, 5, 7, 9]
Explanation: For query 3, the possible items are [3, 5] and [2, 8]. The maximum beauty is 8. Similarly, for query 5, the possible items are [3, 5], [5, 7], and [2, 8]. The maximum beauty is 7.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus