LC 1046 - Last Stone Weight
Question
You are given an array of integers stones where stones[i] is the weight of the ith stone.
We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is:
- If
x == y, both stones are destroyed, and - If
x != y, the stone of weightxis destroyed, and the stone of weightyhas new weighty - x.
At the end of the game, there is at most one stone left.
Return the weight of the last remaining stone. If there are no stones left, return 0.
Example 1:
1
2
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 value of the last stone.
Example 2:
1
2
Input: stones = [1]
Output: 1
Constraints:
1 <= stones.length <= 301 <= stones[i] <= 1000
Links
Question here and solution here
Solution
concept
Use a max heap to solve this question
code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
max_heap = [-1*stone for stone in stones]
heapq.heapify(max_heap)
while len(max_heap) > 1:
stone_1 = heapq.heappop(max_heap)
stone_2 = heapq.heappop(max_heap)
if stone_1 != stone_2:
diff = stone_1 - stone_2
heapq.heappush(max_heap, diff)
return -1*max_heap[0] if max_heap else 0
class NeetSolution:
def lastStoneWeight(self, stones: List[int]) -> int:
stones = [-s for s in stones]
heapq.heapify(stones)
while len(stones) > 1:
first = heapq.heappop(stones)
second = heapq.heappop(stones)
if second > first:
heapq.heappush(stones, first - second)
# for edge case where no stone is left after the loop
stones.append(0)
return abs(stones[0])
Complexity
time: $O(n \log n)$
space: $O(n)$