algoadvance

Leetcode 2558. Take Gifts From the Richest Pile

Problem Statement

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.

Clarifying Questions

  1. Are all elements in the gifts array positive integers?
    • Yes, every pile will have a positive integer number of gifts.
  2. What if there are multiple piles with the same maximum number of gifts?
    • We can choose any one of those piles.
  3. Can k be larger than the length of the gifts array?
    • Yes, but k is the number of turns to perform the operation and is not directly related to the number of piles.
  4. What should the function return if k is zero?
    • It should return the sum of the gifts across all piles, as no operations are performed.

Strategy

  1. Use a priority queue (max-heap) to efficiently get the pile with the maximum number of gifts.
  2. For each turn (up to k):
    • Extract the maximum element from the heap.
    • Calculate the number of gifts to take using floor(sqrt(max_gifts)).
    • Subtract the number of taken gifts from the maximum element.
    • Push the remaining gifts back into the heap.
  3. After k turns, sum all the remaining elements in the heap to get the total number of gifts left.

Code

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;
    }
}

Time Complexity

Thus, the overall time complexity is O(k log n).

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI