Arena / Problems /

1049. Last Stone Weight II

Medium 0/10 Thrones Claimed
Prev Next

Problem Specification

LeetCode #1049

You are given an array of integers stones where stones[i] is the weight of the i-th 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:

  • If x == y, both stones are destroyed, and
  • If x != 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.

Example 1
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.

Example 2
Input: stones = [31,26,33,21,40]
Output: 5
Constraints

1 <= stones.length <= 30
1 <= stones[i] <= 100

Hints (2)
Hint 1

Think of the final answer as a sum of weights with + or - sign symbols in front of each weight. Actually, all sums with 1 of each sign symbol are possible.

Hint 2

Use dynamic programming: for every possible sum with N stones, those sums +x or -x is possible with N+1 stones, where x is the value of the newest stone. (This overcounts sums that are all positive or all negative, but those don't matter.)

⚔️

Vacant Python Throne

No developer has claimed the Python throne for LeetCode #1049 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Traverse "dp" from right to left by Anonymous Developer
0
Approach Intuition:
  • This problem can be solved by brute force, that is, find all subsets of the array, see if the sum of each subset array is close to half of the sum of the complete array, and find the one that is closest. But when we see stones.length <= 30, we know that such a solution will definitely time out.
  • So we need to change our thinking. The question is equivalent to finding the minimum difference between the sums of the two arrays after splitting. If we find a subset array whose sum is closest to half of the sum of the complete array, then it is the subset array we want.
  • Then this problem will become a 0/1 Knapsack Problem.
class Solution:
    def lastStoneWeightII(self, stones: List[int]) -> int:
        sum_ = sum(stones)

        dp = [False] * (sum_ // 2 + 1)
        dp[0] = True

        for stone in stones:
            # If not traversing in reverse order, the newly assigned value `dp[j]` will act as `dp[j - stone]` later,
            # then the subsequent `dp[j]` will be affected. But each `stone` can only be used once!
            for j in range(len(dp) - 1, 0, -1):
                if j < stone:
                    break
                dp[j] = dp[j] or dp[j - stone]

        for i in range(len(dp) - 1, -1, -1):
            if dp[i]:
                return sum_ - i * 2
#2 Traverse "dp" from Left to Right (Recommended) by Anonymous Developer
0
Approach Intuition:

In solution 1, the traversal order is from right to left which really matters.

During the interview, you need to remember it. Is there any way to not worry about the traversal order?

Click to view the answer

As long as you copy the original dp and reference the value of the copy, you don't have to worry about the original dp value being modified.

class Solution:
    def lastStoneWeightII(self, stones: List[int]) -> int:
        sum_ = sum(stones)

        dp = [False] * (sum_ // 2 + 1)
        dp[0] = True

        for stone in stones:
            dc = dp.copy()

            for j in range(stone, len(dp)):
                dp[j] = dc[j] or dc[j - stone]

        for i in range(len(dp) - 1, -1, -1):
            if dp[i]:
                return sum_ - i * 2
⚔️

Vacant C# Throne

No developer has claimed the C# throne for LeetCode #1049 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Traverse "dp" from right to left by Anonymous Developer
0
Approach Intuition:
  • This problem can be solved by brute force, that is, find all subsets of the array, see if the sum of each subset array is close to half of the sum of the complete array, and find the one that is closest. But when we see stones.length <= 30, we know that such a solution will definitely time out.
  • So we need to change our thinking. The question is equivalent to finding the minimum difference between the sums of the two arrays after splitting. If we find a subset array whose sum is closest to half of the sum of the complete array, then it is the subset array we want.
  • Then this problem will become a 0/1 Knapsack Problem.
public class Solution {
    public int LastStoneWeightII(int[] stones) {
        var sum = stones.Sum();

        var dp = new bool[sum / 2 + 1];
        dp[0] = true;

        foreach (int stone in stones) {
            for (var j = dp.GetUpperBound(0); j >= stone; j--) {
                dp[j] = dp[j] || dp[j - stone];
            }
        }

        for (var j = dp.GetUpperBound(0); j >= 0; j--) {
            if (dp[j]) {
                return sum - j * 2;
            }
        }

        throw new ArithmeticException("lastStoneWeightII() has a logical error!");
    }
}
#2 Traverse "dp" from Left to Right (Recommended) by Anonymous Developer
0
Approach Intuition:

In solution 1, the traversal order is from right to left which really matters.

During the interview, you need to remember it. Is there any way to not worry about the traversal order?

Click to view the answer

As long as you copy the original dp and reference the value of the copy, you don't have to worry about the original dp value being modified.

public class Solution
{
    public int LastStoneWeightII(int[] stones)
    {
        int sum = stones.Sum();

        var dp = new bool[sum / 2 + 1];
        dp[0] = true;

        foreach (int stone in stones)
        {
            var dc = (bool[]) dp.Clone();

            for (var j = stone; j < dp.Length; j++)
            {
                dp[j] = dc[j] || dc[j - stone];
            }
        }

        for (var j = dp.GetUpperBound(0); j >= 0; j--)
        {
            if (dp[j])
            {
                return sum - j * 2;
            }
        }

        throw new ArithmeticException("lastStoneWeightII() has a logical error!");
    }
}
⚔️

Vacant C++ Throne

No developer has claimed the C++ throne for LeetCode #1049 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Traverse "dp" from right to left by Anonymous Developer
0
Approach Intuition:
  • This problem can be solved by brute force, that is, find all subsets of the array, see if the sum of each subset array is close to half of the sum of the complete array, and find the one that is closest. But when we see stones.length <= 30, we know that such a solution will definitely time out.
  • So we need to change our thinking. The question is equivalent to finding the minimum difference between the sums of the two arrays after splitting. If we find a subset array whose sum is closest to half of the sum of the complete array, then it is the subset array we want.
  • Then this problem will become a 0/1 Knapsack Problem.
class Solution {
public:
    int lastStoneWeightII(vector<int>& stones) {
        auto sum = reduce(stones.begin(), stones.end());

        auto dp = vector<bool>(sum / 2 + 1);
        dp[0] = true;

        for (auto stone : stones) {
            for (auto j = dp.size() - 1; j >= stone; j--) {
                dp[j] = dp[j] || dp[j - stone];
            }
        }

        for (auto i = dp.size() - 1; i >= 0; i--) {
            if (dp[i]) {
                return sum - i * 2;
            }
        }

        throw logic_error("lastStoneWeightII() has a logical error!");
    }
};
#2 Traverse "dp" from Left to Right (Recommended) by Anonymous Developer
0
Approach Intuition:

In solution 1, the traversal order is from right to left which really matters.

During the interview, you need to remember it. Is there any way to not worry about the traversal order?

Click to view the answer

As long as you copy the original dp and reference the value of the copy, you don't have to worry about the original dp value being modified.

class Solution {
public:
    int lastStoneWeightII(vector<int>& stones) {
        auto sum = reduce(stones.begin(), stones.end());

        auto dp = vector<bool>(sum / 2 + 1);
        dp[0] = true;

        for (auto stone : stones) {
            auto dc = dp;

            for (auto j = stone; j < dp.size(); j++) {
                dp[j] = dc[j] || dc[j - stone];
            }
        }

        for (auto i = dp.size() - 1; i >= 0; i--) {
            if (dp[i]) {
                return sum - i * 2;
            }
        }

        throw logic_error("lastStoneWeightII() has a logical error!");
    }
};
⚔️

Vacant Java Throne

No developer has claimed the Java throne for LeetCode #1049 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Traverse "dp" from right to left by Anonymous Developer
0
Approach Intuition:
  • This problem can be solved by brute force, that is, find all subsets of the array, see if the sum of each subset array is close to half of the sum of the complete array, and find the one that is closest. But when we see stones.length <= 30, we know that such a solution will definitely time out.
  • So we need to change our thinking. The question is equivalent to finding the minimum difference between the sums of the two arrays after splitting. If we find a subset array whose sum is closest to half of the sum of the complete array, then it is the subset array we want.
  • Then this problem will become a 0/1 Knapsack Problem.
class Solution {
    public int lastStoneWeightII(int[] stones) {
        var sum = IntStream.of(stones).sum();

        var dp = new boolean[sum / 2 + 1];
        dp[0] = true;

        for (var stone : stones) {
            for (var j = dp.length - 1; j >= stone; j--) {
                dp[j] = dp[j] || dp[j - stone];
            }
        }

        for (var j = dp.length - 1; j >= 0; j--) {
            if (dp[j]) {
                return sum - j * 2;
            }
        }

        throw new ArithmeticException("lastStoneWeightII() has a logical error!");
    }
}
#2 Traverse "dp" from Left to Right (Recommended) by Anonymous Developer
0
Approach Intuition:

In solution 1, the traversal order is from right to left which really matters.

During the interview, you need to remember it. Is there any way to not worry about the traversal order?

Click to view the answer

As long as you copy the original dp and reference the value of the copy, you don't have to worry about the original dp value being modified.

class Solution {
    public int lastStoneWeightII(int[] stones) {
        var sum = IntStream.of(stones).sum();

        var dp = new boolean[sum / 2 + 1];
        dp[0] = true;

        for (var stone : stones) {
            var dc = dp.clone();

            for (var j = stone; j < dp.length; j++) {
                dp[j] = dc[j] || dc[j - stone];
            }
        }

        for (var j = dp.length - 1; j >= 0; j--) {
            if (dp[j]) {
                return sum - j * 2;
            }
        }

        throw new ArithmeticException("lastStoneWeightII() has a logical error!");
    }
}
⚔️

Vacant Javascript Throne

No developer has claimed the Javascript throne for LeetCode #1049 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Traverse "dp" from right to left by Anonymous Developer
0
Approach Intuition:
  • This problem can be solved by brute force, that is, find all subsets of the array, see if the sum of each subset array is close to half of the sum of the complete array, and find the one that is closest. But when we see stones.length <= 30, we know that such a solution will definitely time out.
  • So we need to change our thinking. The question is equivalent to finding the minimum difference between the sums of the two arrays after splitting. If we find a subset array whose sum is closest to half of the sum of the complete array, then it is the subset array we want.
  • Then this problem will become a 0/1 Knapsack Problem.
var lastStoneWeightII = function (stones) {
  const sum = _.sum(stones)

  const dp = Array(Math.floor(sum / 2) + 1).fill(false)
  dp[0] = true

  for (const stone of stones) {
    for (let j = dp.length - 1; j >= stone; j--) {
      dp[j] = dp[j] || dp[j - stone]
    }
  }

  for (let j = dp.length - 1; j >= 0; j--) {
    if (dp[j]) {
      return sum - j * 2
    }
  }
};
#2 Traverse "dp" from Left to Right (Recommended) by Anonymous Developer
0
Approach Intuition:

In solution 1, the traversal order is from right to left which really matters.

During the interview, you need to remember it. Is there any way to not worry about the traversal order?

Click to view the answer

As long as you copy the original dp and reference the value of the copy, you don't have to worry about the original dp value being modified.

var lastStoneWeightII = function (stones) {
  const sum = _.sum(stones)

  const dp = Array(Math.floor(sum / 2) + 1).fill(false)
  dp[0] = true

  for (const stone of stones) {
    const dc = [...dp]

    for (let j = stone; j < dp.length; j++) {
      dp[j] = dc[j] || dc[j - stone]
    }
  }

  for (let j = dp.length - 1; j >= 0; j--) {
    if (dp[j]) {
      return sum - j * 2
    }
  }
};
⚔️

Vacant Go Throne

No developer has claimed the Go throne for LeetCode #1049 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Traverse "dp" from right to left by Anonymous Developer
0
Approach Intuition:
  • This problem can be solved by brute force, that is, find all subsets of the array, see if the sum of each subset array is close to half of the sum of the complete array, and find the one that is closest. But when we see stones.length <= 30, we know that such a solution will definitely time out.
  • So we need to change our thinking. The question is equivalent to finding the minimum difference between the sums of the two arrays after splitting. If we find a subset array whose sum is closest to half of the sum of the complete array, then it is the subset array we want.
  • Then this problem will become a 0/1 Knapsack Problem.
func lastStoneWeightII(stones []int) int {
    sum := 0
    for _, stone := range stones {
        sum += stone
    }

    dp := make([]bool, sum / 2 + 1)
    dp[0] = true

    for _, stone := range stones {
        for j := len(dp) - 1; j >= stone; j-- {
            dp[j] = dp[j] || dp[j - stone]
        }
    }

    for j := len(dp) - 1; j >= 0; j-- {
        if dp[j] {
            return sum - j * 2
        }
    }

    return -1 // This line should be unreachable. It represents function has a logical error.
}
#2 Traverse "dp" from Left to Right (Recommended) by Anonymous Developer
0
Approach Intuition:

In solution 1, the traversal order is from right to left which really matters.

During the interview, you need to remember it. Is there any way to not worry about the traversal order?

Click to view the answer

As long as you copy the original dp and reference the value of the copy, you don't have to worry about the original dp value being modified.

func lastStoneWeightII(stones []int) int {
    sum := 0
    for _, stone := range stones {
        sum += stone
    }

    dp := make([]bool, sum / 2 + 1)
    dp[0] = true

    for _, stone := range stones {
        dc := slices.Clone(dp)

        for j := stone; j < len(dp); j++ {
            dp[j] = dc[j] || dc[j - stone]
        }
    }

    for j := len(dp) - 1; j >= 0; j-- {
        if dp[j] {
            return sum - j * 2
        }
    }

    return -1 // This line should be unreachable. It represents function has a logical error.
}
⚔️

Vacant Ruby Throne

No developer has claimed the Ruby throne for LeetCode #1049 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Traverse "dp" from right to left by Anonymous Developer
0
Approach Intuition:
  • This problem can be solved by brute force, that is, find all subsets of the array, see if the sum of each subset array is close to half of the sum of the complete array, and find the one that is closest. But when we see stones.length <= 30, we know that such a solution will definitely time out.
  • So we need to change our thinking. The question is equivalent to finding the minimum difference between the sums of the two arrays after splitting. If we find a subset array whose sum is closest to half of the sum of the complete array, then it is the subset array we want.
  • Then this problem will become a 0/1 Knapsack Problem.
def last_stone_weight_ii(stones)
  sum = stones.sum

  dp = Array.new(sum / 2 + 1, false)
  dp[0] = true

  stones.each do |stone|
    (1...dp.size).reverse_each do |j|
      break if j < stone

      dp[j] = dp[j] || dp[j - stone]
    end
  end

  (0...dp.size).reverse_each do |j|
    return sum - j * 2 if dp[j]
  end
end
#2 Traverse "dp" from Left to Right (Recommended) by Anonymous Developer
0
Approach Intuition:

In solution 1, the traversal order is from right to left which really matters.

During the interview, you need to remember it. Is there any way to not worry about the traversal order?

Click to view the answer

As long as you copy the original dp and reference the value of the copy, you don't have to worry about the original dp value being modified.

def last_stone_weight_ii(stones)
  sum = stones.sum

  dp = Array.new(sum / 2 + 1, false)
  dp[0] = true

  stones.each do |stone|
    dc = dp.clone

    (stone...dp.size).each do |j|
      dp[j] = dc[j] || dc[j - stone]
    end
  end

  (0...dp.size).reverse_each do |j|
    return sum - j * 2 if dp[j]
  end
end
⚔️

Vacant Rust Throne

No developer has claimed the Rust throne for LeetCode #1049 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

⚔️

Vacant Swift Throne

No developer has claimed the Swift throne for LeetCode #1049 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

⚔️

Vacant Kotlin Throne

No developer has claimed the Kotlin throne for LeetCode #1049 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.