LeetCode 1049: Last Stone Weight II Solution
Master LeetCode problem 1049 (Last Stone Weight II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1049. Last Stone Weight II
Problem Explanation
Explanation
To solve this problem, we can reframe it as a subset sum problem. We need to divide the stones into two groups such that their weights are as close as possible. This is equivalent to finding a subset with the sum closest to half of the total sum of all stones. We can use dynamic programming to solve this problem efficiently.
- Calculate the total sum of all stones.
- Initialize a dp array of size half of the total sum + 1 to represent if a subset sum can be achieved using stones.
- For each stone, update the dp array with the possible subset sums.
- The answer will be the difference between the total sum and twice the largest subset sum that can be achieved.
Time complexity: O(n * sum/2), where n is the number of stones and sum is the total sum of all stones. Space complexity: O(sum/2) for the dp array.
Solution Code
class Solution {
public int lastStoneWeightII(int[] stones) {
int totalSum = 0;
for (int stone : stones) {
totalSum += stone;
}
int target = totalSum / 2;
boolean[] dp = new boolean[target + 1];
dp[0] = true;
for (int stone : stones) {
for (int i = target; i >= stone; i--) {
dp[i] = dp[i] || dp[i - stone];
}
}
for (int i = target; i >= 0; i--) {
if (dp[i]) {
return totalSum - 2 * i;
}
}
return totalSum;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1049 (Last Stone Weight II)?
This page provides optimized solutions for LeetCode problem 1049 (Last Stone Weight II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1049 (Last Stone Weight II)?
The time complexity for LeetCode 1049 (Last Stone Weight II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1049 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1049 in Java, C++, or Python.