Problem Description
Given an array of stones where each stone's weight is represented by an integer, we repeatedly take two stones and smash them together. If the stones have equal weight, both are destroyed; otherwise, the lighter stone is completely destroyed, and the heavier stone's new weight becomes the difference between the two. The goal is to compute the minimum possible weight of the remaining stone (or 0 if no stones remain) after performing a series of such operations optimally.
Key Insights
- The problem can be reinterpreted as a partition problem where we divide the stones into two groups, and the result is the difference between the sums of these two groups.
- The optimal result is achieved when the difference between the two group sums is minimized.
- By framing the problem this way, it becomes a variant of the classic subset sum / knapsack problem.
- Use Dynamic Programming (DP) to find the best achievable subset sum that does not exceed half of the total sum of all stones.
Space and Time Complexity
Time Complexity: O(n * S) where n is the number of stones and S is the total sum of stones. Space Complexity: O(S), where S is the total sum of stones (DP array space).
Solution
We convert the problem into a subset sum problem:
- Compute the total sum of the stones.
- Use a DP array to record which subset sums are possible.
- Iterate through each stone and update the DP array in reverse order to ensure each stone is used only once.
- Find the largest subset sum (s1) that does not exceed half of the total sum.
- The answer is the difference between the total sum and twice this subset sum (total - 2 * s1), representing the minimum remaining weight.