Last Stone Weight II
Problem Statement
You have a pile of stones, and each stone has a weight. In one turn, pick any two stones and smash them together:
- If they weigh the same, both stones are gone.
- If one weighs
xand the other weighsy, withx < y, the lighter stone is gone and the heavier one now weighsy − x.
Keep smashing until at most one stone is left. Return the smallest weight the last stone can have. If no stone is left, return 0.
An array stones, where stones[i] is the weight of stone i.
The smallest weight the last stone can have, or 0 if no stone is left. The function is int lastStoneWeightII(vector<int>& stones).
Smash 4 with 2 (left 2), then 8 with 7 (left 1), then 2 with 1 (left 1). Two 1s are left, and they cancel. The last stone weighs 1, and no order does better.
Put 40 and 33 in one group (sum 73) and 31, 26 and 21 in the other (sum 78). The gap between the groups is 5, and that is the best the last stone can do.
- • 1 ≤ stones.length ≤ 30
- • 1 ≤ stones[i] ≤ 100
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Give every stone a + or − sign; the last weight is the smallest |signed sum|
Find the largest subset sum ≤ total / 2 with one row; the answer is total − 2s
Each smash replaces two stones by their difference, so every stone left is a signed sum of the original stones. Try all 2^N sign patterns, take the absolute value of each sum, and keep the smallest. The order of the smashes never needs checking, because the best sign pattern can always be reached.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like DP — Knapsack translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.