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:
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.
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.
1 <= stones.length <= 30
1 <= stones[i] <= 100
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.
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.)
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.
stones.length <= 30, we know that such a solution will definitely time out.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
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?
As long as you copy the original Click to view the answer
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
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.
stones.length <= 30, we know that such a solution will definitely time out.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!");
}
}
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?
As long as you copy the original Click to view the answer
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!");
}
}
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.
stones.length <= 30, we know that such a solution will definitely time out.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!");
}
};
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?
As long as you copy the original Click to view the answer
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!");
}
};
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.
stones.length <= 30, we know that such a solution will definitely time out.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!");
}
}
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?
As long as you copy the original Click to view the answer
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!");
}
}
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.
stones.length <= 30, we know that such a solution will definitely time out.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
}
}
};
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?
As long as you copy the original Click to view the answer
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
}
}
};
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.
stones.length <= 30, we know that such a solution will definitely time out.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.
}
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?
As long as you copy the original Click to view the answer
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.
}
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.
stones.length <= 30, we know that such a solution will definitely time out.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
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?
As long as you copy the original Click to view the answer
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
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.
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.
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.