Untitled
unknown
plain_text
2 years ago
660 B
8
Indexable
int lastStoneWeight(vector<int>& weights) {
// Convert the weights vector into a max heap (priority queue)
priority_queue<int> max_heap(weights.begin(), weights.end());
while (max_heap.size() > 1) {
int stone1 = max_heap.top();
max_heap.pop();
int stone2 = max_heap.top();
max_heap.pop();
if (stone1 != stone2) {
// Push the difference of the two stones back into the heap
max_heap.push(stone1 - stone2);
}
}
// If the heap is empty, return 0; otherwise, return the top element
return max_heap.empty() ? 0 : max_heap.top();
}
Editor is loading...