Untitled

mail@pastecode.io avatar
unknown
plain_text
5 months ago
660 B
2
Indexable
Never
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();
}