16. Last Stone Weight II
We have a collection of rocks, each rock has a positive integer weight.
Each turn, we choose any two rocks and smash them together. Suppose the stones have weights x
and y
with x <= y
. The result of this smash is:
If
x == y
, both stones are totally destroyed;If
x != y
, the stone of weightx
is totally destroyed, and the stone of weighty
has new weighty-x
.
At the end, there is at most 1 stone left. Return the smallest possible weight of this stone (the weight is 0 if there are no stones left.)
Example 1:
Solution: (DP)
Find two subset such that abs(S2 - S1) is minimum
s1 + s2 = sum dif = (s2 - s1) dif = (sum - 2 * s1) [Nee to minimize this value] assuming s1 <= sum/2 This problem is same as subset sum: Finding all possible sum formed and minimizing the difference.
Time Complexity: O(n * m)
Last updated