-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode-LastStoneWeight.cpp
More file actions
34 lines (33 loc) · 1.04 KB
/
LeetCode-LastStoneWeight.cpp
File metadata and controls
34 lines (33 loc) · 1.04 KB
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
class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
if (stones.size() >= 3) {
make_heap(stones.begin(), stones.end());
int r = stones.front();
pop_heap(stones.begin(), stones.end());
stones.pop_back();
while (stones.size() >= 1 && r > 0) {
int m = stones.front();
pop_heap(stones.begin(), stones.end());
stones.pop_back();
r -= m;
if (r > 0) {
stones.push_back(r);
push_heap(stones.begin(), stones.end());
}
if (stones.size() == 0) break;
r = stones.front();
pop_heap(stones.begin(), stones.end());
stones.pop_back();
}
return r > 0?r:0;
}
if (stones.size() == 2) {
return abs(stones[1] - stones[0]);
}
if (stones.size() == 1) {
return stones[0];
}
return -1;
}
};