Sponsored
Sponsored
This approach uses a max-heap (priority queue) to efficiently track and retrieve the two heaviest stones. By inserting stones with negative values, we use a min-heap implementation in certain languages to simulate max-heap behavior.
Time Complexity: O(n log n), where n is the number of stones. This accounts for the heap operations.
Space Complexity: O(n), to maintain the heap of stones.
1#include <vector>
2#include <queue>
3
4class Solution {
5public:
6 int lastStoneWeight(std::vector<int>& stones) {
7 std::priority_queue<int> maxHeap(stones.begin(), stones.end());
8 while (maxHeap.size() > 1) {
9 int first = maxHeap.top(); maxHeap.pop();
10 int second = maxHeap.top(); maxHeap.pop();
11 if (first != second) {
12 maxHeap.push(first - second);
13 }
14 }
15 return maxHeap.empty() ? 0 : maxHeap.top();
16 }
17};
This C++ solution utilizes std::priority_queue
to simulate a max-heap, smashing the heaviest stones and re-inserting the results of the smashes until one or no stones remain.
This approach uses a multiset or bag (analogous to balanced trees or sorted lists in some languages) to manage dynamically sorted stone weights. This allows for direct access to largest elements and supports efficient inserts/removals without full re-sorting.
Time Complexity: O(n^2), due to insert and remove operations in SortedList being O(log n).
Space Complexity: O(n), for storage within the SortedList.
1
JavaScript once again calls upon sort
operations for managing stone weights consistently, advising a somewhat static sort approach for interim-based weight comparison checks continuously as we process.