Leetcode 2558. Take Gifts From the Richest Pile
You are given an integer array gifts
representing the number of gifts in several piles. Every seconds you select the richest pile and reduce the number of gifts from that pile to its integer square root. You are allowed to perform this operation k
times in total. Return the total number of gifts remaining after k
operations.
Example:
Example 1:
Input: gifts = [25,64,9,4,100], k = 4
Output: 29
Example 2:
Input: gifts = [1,1,1], k = 3
Output: 3
gifts
contain zero or negative numbers?
gifts
contains only positive integers.k
always be less than or equal to the number of elements in gifts
?
k
can be greater than the number of elements in gifts
.k
operations.#include <vector>
#include <queue>
#include <cmath>
using namespace std;
class Solution {
public:
int totalGifts(vector<int>& gifts, int k) {
// Use max heap (priority queue) to keep track of the richest piles
priority_queue<int> heap(gifts.begin(), gifts.end());
for (int i = 0; i < k; ++i) {
// Extract the richest pile
int richest = heap.top();
heap.pop();
// Reduce the number of gifts in the richest pile to its integer square root
int reduced_gifts = static_cast<int>(sqrt(richest));
// Push the reduced pile back into the heap
heap.push(reduced_gifts);
}
// Calculate the total number of gifts remaining
int total_sum = 0;
while (!heap.empty()) {
total_sum += heap.top();
heap.pop();
}
return total_sum;
}
};
O(n)
.O(log n)
.k
times, this part of the algorithm runs in O(k log n)
.Therefore, the overall time complexity of this solution is O(n + k log n)
.
By following this strategy and using the provided solution, we can efficiently compute the total number of gifts remaining after performing the given operations.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?