2070. Most Beautiful Item for Each Query #822
-
Topics: You are given a 2D integer array You are also given a 0-indexed integer array Return an array Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use sorting and binary search techniques. Here’s the plan: Approach
Let's implement this solution in PHP: 2070. Most Beautiful Item for Each Query <?php
/**
* @param Integer[][] $items
* @param Integer[] $queries
* @return Integer[]
*/
function maximumBeauty($items, $queries) {
// Sort items by price first, and if price is the same, by beauty descending
usort($items, function($a, $b) {
return $a[0] == $b[0] ? $b[1] - $a[1] : $a[0] - $b[0];
});
// Pair queries with their original indices
$indexedQueries = [];
foreach ($queries as $index => $query) {
$indexedQueries[] = [$query, $index];
}
// Sort queries by price
usort($indexedQueries, function($a, $b) {
return $a[0] - $b[0];
});
$maxBeauty = 0;
$itemIndex = 0;
$answer = array_fill(0, count($queries), 0);
// Process each query
foreach ($indexedQueries as $query) {
list($queryPrice, $queryIndex) = $query;
// Move the item pointer to include all items with price <= queryPrice
while ($itemIndex < count($items) && $items[$itemIndex][0] <= $queryPrice) {
$maxBeauty = max($maxBeauty, $items[$itemIndex][1]);
$itemIndex++;
}
// Set the result for this query's original index
$answer[$queryIndex] = $maxBeauty;
}
return $answer;
}
// Example usage
$items = [[1,2],[3,2],[2,4],[5,6],[3,5]];
$queries = [1,2,3,4,5,6];
print_r(maximumBeauty($items, $queries));
// Output: [2,4,5,5,6,6]
?> Explanation:
Complexity
This solution is efficient and meets the constraints of the problem. |
Beta Was this translation helpful? Give feedback.
We can use sorting and binary search techniques. Here’s the plan:
Approach
Sort the Items by Price:
items
by theirprice
. This way, as we iterate through the items, we can keep track of the maximum beauty seen so far for items up to any given price.Sort the Queries with their Original Indices:
price
and avoid recalculating beauty values for lower prices repeatedly.Iterate through Items and Queries Simultaneously: