Untitled
#include <iostream> #include <vector> #include <queue> using namespace std; int lastStoneWeight(int n, vector<int>& stones) { priority_queue<int> maxHeap(stones.begin(), stones.begin() + n); while (maxHeap.size() > 1) { int stoneOne = maxHeap.top(); maxHeap.pop(); int stoneTwo = maxHeap.top(); maxHeap.pop(); if (stoneOne != stoneTwo) { maxHeap.push(stoneOne - stoneTwo); } } return maxHeap.empty() ? 0 : maxHeap.top(); } int main() { vector<int> stones = {2, 4, 5}; int n = stones.size(); cout << "Last stone weight is: " << lastStoneWeight(n, stones) << endl; return 0; }
Leave a Comment