Most Beautiful Item for Each Query

Updated on 19 June, 2025
Most Beautiful Item for Each Query header image

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 <= 105
  • items[i].length == 2
  • 1 <= pricei, beautyi, queries[j] <= 109

Approach and Intuition

To solve this problem effectively, one would typically follow these steps:

  1. Start by sorting the items array primarily by price in ascending order. This allows us to efficiently query items below a certain price threshold.

  2. 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.

  3. 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 items list.
    • If a price has no items below or equal to it (i.e., it is below the price of the cheapest item), answer with 0 for 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
cpp
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 products array 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 indexedRequests array from the requests. 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 indexedRequests based on cost. This sorting helps to process queries in the order of their potential spending limit, aligning with the ordered products array.

  • 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 products as long as the cost of products is less than or equal to the query limit.
    • Update the highestBeauty whenever a more beautiful product within the cost limit is encountered.
    • Assign this highestBeauty value to the correct position in the result vector based on the original index from indexedRequests.
  • Finally, return the result vector 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.

java
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:

  1. Initialize an array results to store the maximum beauty value for each query based on the allowed maximum price.

  2. Sort the products array based on their price in ascending order to streamline the search process.

  3. Prepare an auxiliary array queryIndices where 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.

  4. Sort the queryIndices array based on the price to process in ascending order.

  5. Utilize a variable maxBeautyYet to keep track of the greatest beauty value observed so far that meets the price condition. Initialize productIndex to navigate through the products array.

  6. 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 maxBeautyYet if the current product's beauty is greater than maxBeautyYet.
    • Increment productIndex to move to the next product.
  7. For each query, assign the maxBeautyYet to the corresponding index in the results array using the original query index stored in queryIndices.

  8. Once all queries are processed, return the results array, 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.

python
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_list consists of pairs where the first element in each pair is the price and the second is the beauty value.
  • price_queries is 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:

  1. Initialize a results list to store maximum beauty values for each query, setting all initial values to 0.
  2. Sort items_list by item prices for efficient comparison.
  3. Create indexed_queries to 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.
  4. Use a pointer to iterate through sorted items_list, comparing item prices to the current query price limit.
  5. Maintain a variable highest_beauty to store the maximum beauty observed that does not exceed the current query price.
  6. For each price in the indexed_queries, traverse the items_list and update highest_beauty if a more beautiful item within the price range is found.
  7. Place the maximum beauty for each price query in the corresponding index of the results list based on the original indices stored in indexed_queries.
  8. Finally, return the results list 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.

Comments

No comments yet.