Algorithm
Problem Name: 1049. Last Stone Weight II
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:
- If
x == y
, both stones are destroyed, and - If
x != y
, the stone of weightx
is destroyed, and the stone of weighty
has new weighty - 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
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public int lastStoneWeightII(int[] stones) {
int sum = 0;
for (int stone : stones) {
sum += stone;
}
int[] dp = new int[sum / 2 + 1];
for (int i = 1; i < = stones.length; i++) {
for (int j = sum / 2; j >= stones[i - 1]; j--) {
dp[j] = Math.max(dp[j], dp[j - stones[i - 1]] + stones[i - 1]);
}
}
return sum - 2 * dp[sum / 2];
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const lastStoneWeightII = function(stones) {
let sum=stones.reduce((a,b)=>a+b)
let dp=Array(sum+1).fill(0)
dp[0]=1
for(let i=0;i < stones.length;i++){
let cur=stones[i]
for(let j=dp.length-1;j>=0;j--){
if(j-stones[i]<0)break
if(dp[j-stones[i]]){
dp[j]=1
}
}
}
let minLen=Infinity
for(let i=0;i < dp.length;i++){
if(dp[i]>{
if(i*2-sum>=0)minLen=Math.min(minLen,i*2-sum)
}
}
return minLen
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def lastStoneWeightII(self, A: List[int]) -> int:
dp = {0}
sumA = sum(A)
for a in A:
dp |= {a + i for i in dp}
return min(abs(sumA - i - i) for i in dp)
Copy The Code &
Try With Live Editor
Input
Output