Take Gifts From the Richest Pile - Problem

You are given an integer array gifts denoting the number of gifts in various piles. Every second, you do the following:

  • Choose the pile with the maximum number of gifts.
  • If there is more than one pile with the maximum number of gifts, choose any.
  • Reduce the number of gifts in the pile to the floor of the square root of the original number of gifts in the pile.

Return the number of gifts remaining after k seconds.

Input & Output

Example 1 — Basic Operation
$ Input: gifts = [25,64,9,4,100], k = 4
Output: 29
💡 Note: Second 1: Take 100 → √100 = 10, array becomes [25,64,9,4,10]. Second 2: Take 64 → √64 = 8, array becomes [25,8,9,4,10]. Second 3: Take 25 → √25 = 5, array becomes [5,8,9,4,10]. Second 4: Take 10 → √10 = 3, array becomes [5,8,9,4,3]. Sum = 5+8+9+4+3 = 29
Example 2 — Single Pile
$ Input: gifts = [1], k = 4
Output: 1
💡 Note: Only one pile with 1 gift. After any number of operations: √1 = 1, so it remains [1]. Sum = 1
Example 3 — Small Values
$ Input: gifts = [4,4,4], k = 2
Output: 8
💡 Note: Second 1: Take any 4 → √4 = 2, array becomes [4,4,2]. Second 2: Take any 4 → √4 = 2, array becomes [2,2,2]. Sum = 2+2+2 = 6. Wait, let me recalculate: [4,4,4] → [2,4,4] → [2,2,4]. Sum = 2+2+4 = 8

Constraints

  • 1 ≤ gifts.length ≤ 103
  • 1 ≤ gifts[i] ≤ 109
  • 1 ≤ k ≤ 103

Visualization

Tap to expand
Take Gifts: Reduce Largest Pile Each SecondInitial:256494← Largest (64)After 1s:25894√64 = 8After 2s:5894√25 = 5Continue for k seconds, then sum remaining giftsFinal Sum: 5 + 8 + 9 + 4 = 26
Understanding the Visualization
1
Input
Array of gift piles and number of seconds k
2
Process
Each second: find max pile, replace with floor(√max)
3
Output
Sum of all remaining gifts after k seconds
Key Takeaway
🎯 Key Insight: Use a max heap to efficiently find the largest pile in O(log n) time instead of scanning the entire array
Asked in
Amazon 15 Microsoft 10 Google 8
23.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen