[LeetCode] Take Gifts From the Richest Pile

2558. Take Gifts From the Richest Pile

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.
  • Leave behind the floor of the square root of the number of gifts in the pile. Take the rest of the gifts.

Return the number of gifts remaining after k seconds.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
long long pickGifts(vector<int>& gifts, int k) {
long long res = 0;
priority_queue<long long> q;
for(auto g : gifts) q.push(g);
while(k--) {
if(q.top() == 1) break;
auto tp = q.top(); q.pop();
q.push(sqrt(tp));
}
while(q.size()) {
res += q.top(); q.pop();
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/02/08/PS/LeetCode/take-gifts-from-the-richest-pile/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.