You are given an array of integers stones
where stones[i]
is the weight of the i
-th stone.
We repeatedly choose the two heaviest stones and smash them together. Suppose the heaviest stones have weights x
and y
with x <= y
. The result of this smash is:
x == y
, both stones are destroyed, andx != y
, a new stone of weight y - x
is placed in the list of stones.At the end of the process, there is at most one stone left. Return the weight of this last remaining stone. If there are no stones left, return 0
.
Input: stones = [2,7,4,1,8,1]
Output: 1
Explanation:
We combine `7` and `8` to get `1` so the array converts to `[2,4,1,1,1]` then,
We combine `2` and `4` to get `2` so the array converts to `[2,1,1,1]` then,
We combine `2` and `1` to get `1` so the array converts to `[1,1,1]` then,
We combine `1` and `1` to get `0` so the array converts to `[1]` then that's the last remaining stone.
0
.To efficiently determine the two heaviest stones repeatedly:
heapq
module implements a min-heap, so we will insert negative weights to simulate a max-heap.Steps:
0
.import heapq
def lastStoneWeight(stones):
# Convert all stones to negative numbers to use heapq as a max-heap
max_heap = [-stone for stone in stones]
heapq.heapify(max_heap)
while len(max_heap) > 1:
# Extract the two largest stones
largest = -heapq.heappop(max_heap)
second_largest = -heapq.heappop(max_heap)
if largest != second_largest:
# The new stone weight to be added back
new_stone = largest - second_largest
# Push the negative of this new stone into the heap
heapq.heappush(max_heap, -new_stone)
# If no stones are left, return 0. Otherwise, return the weight of the remaining stone.
return -max_heap[0] if max_heap else 0
Thus, the overall time complexity is O(n log n).
This solution efficiently manages the repeated extraction and insertion of stones based on their weights using a max-heap simulated by a min-heap with negative values.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?