[LeetCode] Remove Stones to Minimize the Total

1962. Remove Stones to Minimize the Total

You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times:

  • Choose any piles[i] and remove floor(piles[i] / 2) stones from it.

Notice that you can apply the operation on the same pile more than once.

Return the minimum possible total number of stones remaining after applying the k operations.

floor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int minStoneSum(vector<int>& piles, int k) {
priority_queue<int> q;
for(auto& p : piles) q.push(p);
while(k--) {
auto p = q.top();q.pop();
q.push(p - p/2);
if(p == 1) break;
}
int res = 0;
while(!q.empty()) {
res += q.top(); q.pop();
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/09/PS/LeetCode/remove-stones-to-minimize-the-total/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.