Reachable sums up to total / 2; the largest reachable s gives total − 2s.
Approach 1
class Solution {
public int lastStoneWeightII(int[] stones) {
int total = 0;
for (int s : stones) total += s;
int half = total / 2;
boolean[] can = new boolean[half + 1];
can[0] = true;
for (int s : stones)
for (int c = half; c >= s; c--) can[c] |= can[c - s];
for (int c = half; ; c--) if (can[c]) return total - 2 * c;
}
}
Verdict: Same code as equal partition.
Before you submit
Edge cases and common mistakes
Test these inputs
One stone
Perfect split (0)
Mistakes people make
Simulating with a heap (that's Last Stone Weight I, a different rule).
Interview
Follow-up questions
Why can every split be achieved by some smashing order?