2558. Take Gifts From the Richest Pile #945
-
Topics: You are given an integer array
Return the number of gifts remaining after Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can utilize a max-heap (priority queue) since we need to repeatedly pick the pile with the maximum number of gifts. A max-heap will allow us to efficiently access the largest pile in constant time and update the heap after taking gifts from the pile. Approach:
Let's implement this solution in PHP: 2558. Take Gifts From the Richest Pile <?php
/**
* @param Integer[] $gifts
* @param Integer $k
* @return Integer
*/
function pickGifts($gifts, $k) {
// Use a max heap implemented using SplPriorityQueue
$maxHeap = new SplPriorityQueue();
// Add all the gifts to the heap
foreach ($gifts as $gift) {
$maxHeap->insert($gift, $gift); // Value and priority are the same
}
// Perform the operation k times
for ($i = 0; $i < $k; ++$i) {
if ($maxHeap->isEmpty()) break;
// Get the largest pile
$largestPile = $maxHeap->extract();
// Compute the floor of the square root of the largest pile
$reducedPile = floor(sqrt($largestPile));
// Put the reduced pile back into the heap
$maxHeap->insert($reducedPile, $reducedPile);
}
// Sum up the remaining gifts
$remainingGifts = 0;
while (!$maxHeap->isEmpty()) {
$remainingGifts += $maxHeap->extract();
}
return $remainingGifts;
}
// Example usage:
$gifts1 = [25, 64, 9, 4, 100];
$k1 = 4;
echo pickGifts($gifts1, $k1) . "\n"; // Output: 29
$gifts2 = [1, 1, 1, 1];
$k2 = 4;
echo pickGifts($gifts2, $k2) . "\n"; // Output: 4
?> Explanation:
Time Complexity:
Thus, the total time complexity is O(k log n), where n is the number of piles and k is the number of seconds. Example Walkthrough:For the input: $gifts = [25, 64, 9, 4, 100];
$k = 4;
The sum of the remaining gifts is 5 + 8 + 9 + 4 + 3 = 29. This approach efficiently solves the problem using a max-heap and performs well within the given constraints. |
Beta Was this translation helpful? Give feedback.
We can utilize a max-heap (priority queue) since we need to repeatedly pick the pile with the maximum number of gifts. A max-heap will allow us to efficiently access the largest pile in constant time and update the heap after taking gifts from the pile.
Approach:
Use a Max-Heap:
SplPriorityQueue
, which is a priority queue that by default works as a max-heap.SplPriorityQueue
is a min-heap by default. By inserting negative values, the smallest negative value will represent…