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 From the Richest Pile INPUT Gift Piles Array: 25 64 9 4 100 [25, 64, 9, 4, 100] Operations: k = 4 Use Max Heap for efficient max finding ALGORITHM STEPS 1 k=1: max=100 floor(sqrt(100))=10 [25,64,9,4,10] 2 k=2: max=64 floor(sqrt(64))=8 [25,8,9,4,10] 3 k=3: max=25 floor(sqrt(25))=5 [5,8,9,4,10] 4 k=4: max=10 floor(sqrt(10))=3 [5,8,9,4,3] Final Sum Calculation: 5+8+9+4+3 = 29 Time: O(k log n) Space: O(n) FINAL RESULT Final Gift Piles: 5 8 9 4 3 Output: 29 OK - Verified Total gifts remaining after 4 operations Key Insight: Using a Max Heap allows O(log n) extraction of the maximum element and reinsertion after transformation. The square root operation rapidly reduces large values, making the algorithm efficient even for large k. Alternative: Sort and iterate, but heap is more efficient when k is smaller than n log n. TutorialsPoint - Take Gifts From the Richest Pile | Optimal Solution (Max Heap)
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