-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path1962.cpp
More file actions
34 lines (33 loc) · 801 Bytes
/
Copy path1962.cpp
File metadata and controls
34 lines (33 loc) · 801 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Using a priority_queue
class Solution {
public:
int minStoneSum(vector<int> &piles, int k) {
priority_queue<int> pq;
int res = 0;
for (int e : piles)
res += e, pq.push(e);
while (k--) {
int t = pq.top(), pq.pop();
pq.push(t - t / 2), res -= t / 2;
}
return res;
}
};
// Using heap, constant memory
class Solution {
public:
int minStoneSum(vector<int> &piles, int k) {
auto b = piles.begin(), e = piles.end();
make_heap(b, e);
while (k--) {
pop_heap(b, e);
auto &elem = *(e - 1);
elem -= elem / 2;
push_heap(b, e);
}
int sum = 0;
for (auto v : piles)
sum += v;
return sum;
}
};