Last Stone Weight - Problem
Imagine you're playing an ancient stone-smashing game! You have a collection of stones, each with a specific weight, and you need to repeatedly smash the two heaviest stones together until at most one stone remains.
Here's how the game works:
- ๐ฏ Choose the two heaviest stones (let's call their weights
xandywherex โค y) - ๐ฅ Smash them together:
- If
x == y: Both stones are completely destroyed - If
x < y: The lighter stone is destroyed, and the heavier stone becomes a new stone with weighty - x
- If
- ๐ Repeat until there's at most one stone left
Goal: Return the weight of the last remaining stone, or 0 if no stones are left.
Example: Stones [2,7,4,1,8,1] โ After all smashing โ Last stone weighs 1
Input & Output
example_1.py โ Standard Case
$
Input:
[2,7,4,1,8,1]
โบ
Output:
1
๐ก Note:
Step by step: [2,7,4,1,8,1] โ smash 8,7 โ [2,4,1,1,1] โ smash 4,2 โ [2,1,1,1] โ smash 2,1 โ [1,1,1] โ smash 1,1 โ [1] โ final answer: 1
example_2.py โ Single Stone
$
Input:
[1]
โบ
Output:
1
๐ก Note:
Only one stone exists, so no smashing occurs. The weight of the last (and only) stone is 1.
example_3.py โ All Stones Destroyed
$
Input:
[3,3]
โบ
Output:
0
๐ก Note:
Both stones have equal weight (3), so when they smash together, both are completely destroyed. No stones remain, so return 0.
Visualization
Tap to expand
Understanding the Visualization
1
Tournament Setup
All fighters (stones) enter the tournament bracket, arranged by strength
2
Championship Match
The two strongest fighters face off in the center ring
3
Battle Result
Either both are eliminated (equal strength) or winner continues with reduced power
4
New Champion
The surviving fighter rejoins the tournament, and the process repeats
Key Takeaway
๐ฏ Key Insight: A max heap maintains the tournament bracket automatically, always keeping the strongest fighters (heaviest stones) ready for the next battle without expensive reorganization.
Time & Space Complexity
Time Complexity
O(n log n)
Building heap takes O(n log n), and each of the n operations takes O(log n) time
โก Linearithmic
Space Complexity
O(n)
The heap stores all stones, requiring O(n) extra space
โก Linearithmic Space
Constraints
- 1 โค stones.length โค 30
- 1 โค stones[i] โค 1000
- All stone weights are positive integers
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code