724. Smallest Leftover Stone
A stone crusher is fed a pile of rocks whose weights are in stones. In every round the operator picks any two rocks and smashes them together. If the weights are equal, both rocks vanish; otherwise only the lighter one vanishes and the heavier one stays, now weighing the difference of the two.
The operator keeps going until at most one rock is left. Return the smallest possible weight of that last rock, or 0 if no rock remains. The operator chooses the pairs freely, so the answer is the best over all possible orders.
Aim for time O(n * S), where S is the total weight, and space O(S).
Example 1
- Input:
- stones = [9,4,7,3,8]
- Output:
- 1
- Explanation:
Group 9+7 against 4+3+8 gives 16 versus 15, so a rock of weight 1 can be left over, and no split is perfectly balanced since the total 31 is odd.
Example 2
- Input:
- stones = [5,5,2,2,6]
- Output:
- 0
- Explanation:
The total is 20 and the groups 5+5 and 2+2+6 each weigh 10, so the rocks can cancel completely and the answer is 0.
Constraints
1 ≤ stones.length ≤ 200
1 ≤ stones[i] ≤ 100
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n * S)
- Space
- O(S)