Leetcode 2558. Take Gifts From the Richest Pile
You are given an array of integers gifts where each element represents the number of gifts in a pile. You are also given an integer k. You must take gifts from the richest pile (the pile with the maximum number of gifts) for k turns. In each turn, you take floor(sqrt(max(gifts))) gifts from that pile and leave the rest in the pile. This action continues for k turns. Return the total number of gifts remaining after k turns.
gifts array positive integers?
k be larger than the length of the gifts array?
k is the number of turns to perform the operation and is not directly related to the number of piles.k is zero?
k):
floor(sqrt(max_gifts)).k turns, sum all the remaining elements in the heap to get the total number of gifts left.import java.util.PriorityQueue;
import java.util.Collections;
public class Solution {
public long remainingGifts(int[] gifts, int k) {
// Max-Heap for storing the gifts piles
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
// Add all gifts to the heap
for (int gift : gifts) {
maxHeap.add(gift);
}
// Perform k operations
for (int i = 0; i < k; i++) {
if (maxHeap.isEmpty()) {
break;
}
int maxGifts = maxHeap.poll();
int giftsTaken = (int) Math.floor(Math.sqrt(maxGifts));
int remainingGifts = maxGifts - giftsTaken;
maxHeap.add(remainingGifts);
}
// Calculate the total remaining gifts
long totalRemainingGifts = 0;
while (!maxHeap.isEmpty()) {
totalRemainingGifts += maxHeap.poll();
}
return totalRemainingGifts;
}
}
k turns, each requiring a removal and an insertion operation, leading to a time complexity of O(k log n), where n is the number of piles.Thus, the overall time complexity is O(k log n).
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?