LeetCode 2558: Take Gifts From the Richest Pile

Problem Description

Explanation:

To solve this problem, we can simulate the process described in the problem statement. At each second, we find the maximum pile and reduce the number of gifts in that pile to the floor of the square root of the original number of gifts. We repeat this process for k seconds and calculate the total number of remaining gifts.

Algorithm:

  1. Initialize a priority queue to store the piles in descending order of gifts.
  2. Add all the piles to the priority queue.
  3. Repeat the following steps for k seconds:
    • Pop the pile with the maximum number of gifts from the priority queue.
    • Calculate the new number of gifts in that pile by taking the floor of the square root of the original number of gifts.
    • If the new number of gifts is greater than 0, add it back to the priority queue.
  4. Calculate the total number of remaining gifts.

Time Complexity:

The time complexity of this algorithm is O(k*log(n)), where n is the number of piles.

Space Complexity:

The space complexity of this algorithm is O(n) for storing the piles in the priority queue.

: :

Solutions

import java.util.*;

class Solution {
    public int maxNumberOfGifts(int[] gifts, int k) {
        PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
        for (int gift : gifts) {
            pq.offer(gift);
        }
        
        for (int i = 0; i < k; i++) {
            int maxGifts = pq.poll();
            int newGifts = (int) Math.floor(Math.sqrt(maxGifts));
            if (newGifts > 0) {
                pq.offer(newGifts);
            }
        }
        
        int totalGifts = 0;
        for (int remainingGifts : pq) {
            totalGifts += remainingGifts;
        }
        
        return totalGifts;
    }
}

Loading editor...