Last Stone Weight
Real-world version: Molten Glass MergeThe statement here is our own: the same inputs, outputs and technique.
A glassworks has a bench of molten gobs; gobs[i] is the weight of gob i in grams.
While at least two gobs are on the bench, the gaffer picks the two heaviest of them, say of weights x and y with x <= y, and presses them together:
- if
x == y, both gobs are spent and nothing is left of either; - otherwise the pair becomes a single gob weighing
y - xgrams.
When two gobs tie for heaviest, it does not matter which is picked. Return the weight of the gob left on the bench when no further press is possible, or 0 if the bench ends up empty.
Examples
Example 1
- Input
- gobs = [3, 7, 2]
- Output
- 2
Pressing 7 with 3 leaves a 4 gram gob, so the bench holds [4, 2]. Pressing 4 with 2 leaves a 2 gram gob, and that is the last one.
Example 2
- Input
- gobs = [10, 4, 3, 2]
- Output
- 1
Pressing 10 with 4 gives [6, 3, 2]; pressing 6 with 3 gives [3, 2]; pressing 3 with 2 leaves a single gram.
Example 3
- Input
- gobs = [2, 2, 2, 2]
- Output
- 0
Each press is between equal weights, so the bench ends up empty.
Example 4
- Input
- gobs = [5]
- Output
- 5
A single gob has no partner, so no press happens and it stays as it is.
Constraints
- 1 <= gobs.length <= 30
- 1 <= gobs[i] <= 1000
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def last_stone_weight(gobs: list[int]) -> int:public int lastStoneWeight(int[] gobs)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 passed
- Passed: 4 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Maximum Product of Two Elements in an ArrayReal-world version: Best Pair Of Voucher PayoutsEasy
- Minimum Number GameReal-world version: Shelving Boxes in TurnsEasy
- High FiveReal-world version: Top Five Average per ApprenticeEasy
- Make Array Zero by Subtracting Equal AmountsReal-world version: Rounds Needed to Clear Every ReadingEasy