
Problem Statement
In this scenario, you are provided with two sets of data. The first set, items, is a list containing sublists where each sublist provides details about an item—specifically, its price and beauty represented as [pricei, beautyi]. The second, queries, is an array of price limits.
Your task is to compute the maximum beauty value for each price limit specified in queries. For each price limit (say queries[j]), you need to identify all the items from the items list whose prices are below or exactly equal to queries[j] and from those, find the item with the highest beauty. If no items qualify under a specific price limit, the answer should be 0 for that query.
The solution should be delivered in the form of an array where each element corresponds to the result of each query based on the conditions mentioned above.
Examples
Example 1
Input:
items = [[1,2],[3,2],[2,4],[5,6],[3,5]], queries = [1,2,3,4,5,6]
Output:
[2,4,5,5,6,6]
Explanation:
- For queries[0]=1, [1,2] is the only item which has price <= 1. Hence, the answer for this query is 2. - For queries[1]=2, the items which can be considered are [1,2] and [2,4]. The maximum beauty among them is 4. - For queries[2]=3 and queries[3]=4, the items which can be considered are [1,2], [3,2], [2,4], and [3,5]. The maximum beauty among them is 5. - For queries[4]=5 and queries[5]=6, all items can be considered. Hence, the answer for them is the maximum beauty of all items, i.e., 6.
Example 2
Input:
items = [[1,2],[1,2],[1,3],[1,4]], queries = [1]
Output:
[4]
Explanation:
The price of every item is equal to 1, so we choose the item with the maximum beauty 4. Note that multiple items can have the same price and/or beauty.
Example 3
Input:
items = [[10,1000]], queries = [5]
Output:
[0]
Explanation:
No item has a price less than or equal to 5, so no item can be chosen. Hence, the answer to the query is 0.
Constraints
1 <= items.length, queries.length <= 105items[i].length == 21 <= pricei, beautyi, queries[j] <= 109
Approach and Intuition
To solve this problem effectively, one would typically follow these steps:
Start by sorting the
itemsarray primarily by price in ascending order. This allows us to efficiently query items below a certain price threshold.Prepare a secondary structure to keep track of the maximum beauty encountered so far as we progress through the sorted item list. This can be done using a list where the index represents prices and the values at each index represent the maximum beauty at or below that price.
Process each query individually:
- For each query, directly refer to our pre-computed structure to fetch the maximum beauty less than or equal to the queried price.
- If the query price is higher than the highest item price, directly take the maximum beauty encountered in the entire
itemslist. - If a price has no items below or equal to it (i.e., it is below the price of the cheapest item), answer with
0for that query.
The examples provided illustrate how this mechanism handles various scenarios:
- When prices correspond closely or exactly to query values.
- When multiple items have identical prices.
- When a query value falls below the price range of available items.
This method ensures that we are not repeatedly searching through the items list for each query, thus optimizing the response time and ensuring efficiency even for larger input sizes, as hinted at by the constraints where lengths can go up to 105 and values can be significantly large.
Solutions
- C++
- Java
- Python
class Solution {
public:
vector<int> getMaximumBeauty(vector<vector<int>>& products,
vector<int>& requests) {
vector<int> result(requests.size());
// ordering products and requests
sort(products.begin(), products.end(),
[](vector<int>& x, vector<int>& y) { return x[0] < y[0]; });
vector<vector<int>> indexedRequests(requests.size(), vector<int>(2));
for (int i = 0; i < requests.size(); i++) {
indexedRequests[i][0] = requests[i];
indexedRequests[i][1] = i;
}
sort(indexedRequests.begin(), indexedRequests.end(),
[](vector<int>& x, vector<int>& y) { return x[0] < y[0]; });
int productIndex = 0;
int highestBeauty = 0;
for (int i = 0; i < requests.size(); i++) {
int currentQuery = indexedRequests[i][0];
int queryIndex = indexedRequests[i][1];
while (productIndex < products.size() && products[productIndex][0] <= currentQuery) {
highestBeauty = max(highestBeauty, products[productIndex][1]);
productIndex++;
}
result[queryIndex] = highestBeauty;
}
return result;
}
};
This C++ solution addresses the problem of finding the most beautiful item for each query from a list of available products. Each product and query includes a cost limit and beauty value. Here’s a concise explanation of how the code achieves this:
First, start by sorting the
productsarray based on their cost in ascending order. This helps in efficiently accessing the maximum beauty that can be obtained within a given cost as encountered in subsequent queries.Next, construct an
indexedRequestsarray from therequests. This array has pairs consisting of the request values together with their original indices. The purpose is to keep track of the original order of requests, as they will be sorted next.Sort the
indexedRequestsbased on cost. This sorting helps to process queries in the order of their potential spending limit, aligning with the orderedproductsarray.Initialize a variable,
highestBeauty, to store the maximum beauty value found so far which fits within the queried limits.Traverse through
indexedRequests:- For each query, while loop through the
productsas long as the cost of products is less than or equal to the query limit. - Update the
highestBeautywhenever a more beautiful product within the cost limit is encountered. - Assign this
highestBeautyvalue to the correct position in the result vector based on the original index fromindexedRequests.
- For each query, while loop through the
Finally, return the
resultvector which contains the maximum beauty values corresponding to each original query in the order they were provided.
By meticulously maintaining order and using a linear scan matched with conditional updates, the solution efficiently matches products' beauty to the appropriate queries' budget constraints, ensuring optimal performance even for larger datasets.
class Solution {
public int[] calculateBeauty(int[][] products, int[] queries) {
int[] results = new int[queries.length];
Arrays.sort(products, (x, y) -> x[0] - y[0]);
int[][] queryIndices = new int[queries.length][2];
for (int i = 0; i < queries.length; i++) {
queryIndices[i][0] = queries[i];
queryIndices[i][1] = i;
}
Arrays.sort(queryIndices, (x, y) -> x[0] - y[0]);
int maxBeautyYet = 0;
int productIndex = 0;
for (int i = 0; i < queries.length; i++) {
int currentQuery = queryIndices[i][0];
int queryOriginalIndex = queryIndices[i][1];
while (productIndex < products.length && products[productIndex][0] <= currentQuery) {
maxBeautyYet = Math.max(maxBeautyYet, products[productIndex][1]);
productIndex++;
}
results[queryOriginalIndex] = maxBeautyYet;
}
return results;
}
}
The given Java solution aims to determine the highest beauty value of items that do not exceed the price specified in each query from a list of products. Each product and query is represented by an integer value where products are defined by a two-dimensional array with price and beauty values, and queries are an array of maximum prices to consider.
Follow these steps to understand how this implementation works:
Initialize an array
resultsto store the maximum beauty value for each query based on the allowed maximum price.Sort the
productsarray based on their price in ascending order to streamline the search process.Prepare an auxiliary array
queryIndiceswhere each element is an array consisting of the query price and its original index. This step helps in mapping the results back to the original query order after processing.Sort the
queryIndicesarray based on the price to process in ascending order.Utilize a variable
maxBeautyYetto keep track of the greatest beauty value observed so far that meets the price condition. InitializeproductIndexto navigate through theproductsarray.Iterate over each query and for each, continually compare the product price to the current query price.
- If the product's price is less than or equal to the query price, update
maxBeautyYetif the current product's beauty is greater thanmaxBeautyYet. - Increment
productIndexto move to the next product.
- If the product's price is less than or equal to the query price, update
For each query, assign the
maxBeautyYetto the corresponding index in theresultsarray using the original query index stored inqueryIndices.Once all queries are processed, return the
resultsarray, which now contains the maximum beauty value for each price specified by the queries.
This algorithm efficiently matches each query with the appropriate maximum beauty value by leveraging sorting and simultaneous tracking of maximum beauty values, ensuring each query is answered in optimal time.
class Solution:
def getMaxBeauty(self, items_list, price_queries):
results = [0] * len(price_queries)
items_list.sort(key=lambda x: x[0])
indexed_queries = [[price_queries[i], i] for i in range(len(price_queries))]
indexed_queries.sort(key=lambda x: x[0])
pointer = 0
highest_beauty = 0
for idx in range(len(indexed_queries)):
current_query = indexed_queries[idx][0]
query_orig_idx = indexed_queries[idx][1]
while pointer < len(items_list) and items_list[pointer][0] <= current_query:
highest_beauty = max(highest_beauty, items_list[pointer][1])
pointer += 1
results[query_orig_idx] = highest_beauty
return results
The provided Python code defines a method to determine the most beautiful item for each query. The beauty of an item is compared and decided based on its price. The function accepts two parameters: items_list and price_queries.
items_listconsists of pairs where the first element in each pair is the price and the second is the beauty value.price_queriesis a list representing price limits for each query to determine the maximum beauty that can be purchased within that limit.
Here's what the code essentially does:
- Initialize a results list to store maximum beauty values for each query, setting all initial values to 0.
- Sort
items_listby item prices for efficient comparison. - Create
indexed_queriesto record original indices of the queries, which helps in placing the maximum beauty values correctly in the result later. This list is also sorted by price. - Use a pointer to iterate through sorted
items_list, comparing item prices to the current query price limit. - Maintain a variable
highest_beautyto store the maximum beauty observed that does not exceed the current query price. - For each price in the
indexed_queries, traverse theitems_listand updatehighest_beautyif a more beautiful item within the price range is found. - Place the maximum beauty for each price query in the corresponding index of the
resultslist based on the original indices stored inindexed_queries. - Finally, return the
resultslist containing the maximum beauty values for each price query.
This solution is efficient, leveraging sorting and linear traversal to resolve the price queries in relation to the beauty and price of the items.