You are given an array of integers stones where stones[i] is the weight of the ith stone.
We are playing a game with the stones. On each turn, we choose any two stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is:
x == y, both stones are destroyed, andx != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.At the end of the game, there is at most one stone left.
Return the smallest possible weight of the left stone. If there are no stones left, return 0.
Input: stones = [2,7,4,1,8,1]
Output: 1
Explanation:
We can combine 2 and 4 to get 2, so the array converts to [2,7,1,8,1] then,
we can combine 7 and 8 to get 1, so the array converts to [2,1,1,1] then,
we can combine 2 and 1 to get 1, so the array converts to [1,1,1] then,
we can combine 1 and 1 to get 0, so the array converts to [1], then that's the optimal value.
Input: stones = [31,26,33,21,40]
Output: 5
Constraints:
1 <= stones.length <= 301 <= stones[i] <= 100The problem can be reduced to a classic "Partition problem" where we need to split the stones into two groups such that their absolute difference in sum is minimized. A recursive approach involves dividing the set of stones into subsets and calculating their possible weights. The main recursive function attempts to either include or exclude a stone in a possible "bucket" or subset and recursively attempts to minimize the difference between two subsets.
sum/2).half as possible from available stones.2*currentSubsetSum and totalSum.n is the number of stones. The recursive function potentially explores all subsets of stones.To improve upon our recursive method, we can utilize a dynamic programming approach similar to solving the subset sum problem. Our task is to find a subset of stones whose sum is as close as possible to sum/2. Using a DP table, we can keep track of the maximum possible sum of stone weights that can be achieved.
half = totalSum / 2: our goal is to find a sum as close as possible to half.dp where dp[j] will maintain whether a sum j can be achieved with available stones.dp[0] = true since a sum of zero can always be achieved without including any stone.half to the stone weight in reverse, updating the DP array.j such that dp[j] is true. The result will be totalSum - 2*j.n is the number of stones and sum is the total sum of stones.