Last stone weight
Warm-up · Write code · about 10 min
Each value in stones is the weight of a stone. Each turn, take the two heaviest stones, y ≥ x. If they weigh the same, both are destroyed. Otherwise x is destroyed and y becomes y - x.
Repeat until at most one stone is left. Return its weight, or 0 when no stone is left.
Example 1
Input:
[[2,7,4,1,8,1]]
Output:
1
8, 7 leave 1; 4, 2 leave 2; 2, 1 leave 1; 1, 1 vanish. One stone of weight 1 is left.
Example 2
Input:
[[3,3]]
Output:
0
Two equal stones destroy each other.
Constraints
- 1 ≤ stones.length ≤ 1,000
- 1 ≤ stones[i] ≤ 1,000
Learn the idea first: Priority queues in practice: top-k, k-way merge, scheduling, a visual lesson.
More Priority queues in practice: top-k, k-way merge, scheduling problems
- Which heap keeps the top k? Warm-up
- K largest values Warm-up
- Merge k sorted lists Standard
- Top k frequent values Standard
- Trace a size-k min-heap Standard
- Task scheduler Challenge