#2070

Most Beautiful Item for Each Query

Medium
ArrayBinary SearchSortingSortingBinary SearchPrefix Maximum
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n + m log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n + m log n)Space O(n)

By sorting the items based on price and using a prefix maximum array for beauty, we can efficiently answer each query in logarithmic time using binary search.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the items by price.
  2. 2Step 2: Create a prefix maximum array for beauty values, where each index corresponds to the maximum beauty up to that price.
  3. 3Step 3: For each query, use binary search to find the rightmost item with a price less than or equal to the query price.
  4. 4Step 4: Return the maximum beauty from the prefix array for the found index; if no valid index is found, return 0.
solution.py11 lines
1def maxBeauty(items, queries):
2    items.sort()
3    max_beauty = [0] * len(items)
4    max_beauty[0] = items[0][1]
5    for i in range(1, len(items)):
6        max_beauty[i] = max(max_beauty[i-1], items[i][1])
7    result = []
8    for q in queries:
9        idx = bisect.bisect_right(items, [q, float('inf')]) - 1
10        result.append(max_beauty[idx] if idx >= 0 else 0)
11    return result

Complexity note: Sorting the items takes O(n log n), and each query takes O(log n) due to binary search, resulting in O(m log n) for m queries.

  • 1Sorting the items allows us to efficiently find the maximum beauty for each price threshold.
  • 2Using a prefix maximum array helps in quickly retrieving the maximum beauty without re-evaluating items.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.