Take Gifts From the Richest Pile

You are given an integer array `gifts`, where `gifts[i]` is the number of gifts in pile `i`. Every second you do this: pick the pile with the most gifts (any of them if several tie), and leave behind `floor(sqrt(x))` gifts of its `x`, taking the rest. Return the number of gifts left in all piles after `k` seconds.

30:00

Take Gifts From the Richest Pile
easy
Free written solution
Topics
Companies

You are given an integer array gifts, where gifts[i] is the number of gifts in pile i. Every second you do this: pick the pile with the most gifts (any of them if several tie), and leave behind floor(sqrt(x)) gifts of its x, taking the rest. Return the number of gifts left in all piles after k seconds.

Example 1:
Input: {"gifts":[25,64,9,4,100],"k":4}
Output: 29
Constraints:
  • 1≤gifts.length≤1031 \leq \text{gifts.length} \leq 10^3

  • 1≤gifts[i]≤1091 \leq \text{gifts}[i] \leq 10^9

  • 1≤k≤1031 \leq k \leq 10^3

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"gifts":[25,64,9,4,100],"k":4}

second 0 / 4

taken 0

left in piles 202

gift piles (height ~ sqrt of size)

25

#0

64

#1

9

#2

4

#3

100

#4

■ richest (heap top)

- - taken this second

5 piles holding 202 gifts. Put them in a max-heap so the richest pile is always on top.

Variables
VariableValue
second0
taken0
DepthFunction Call
Stack empty
0/9