Last Stone Weight II (Leetcode 1049)
Problem Link: https://leetcode.com/problems/last-stone-weight-ii/
class Solution:
def lastStoneWeightII(self, stones: List[int]) -> int:
# Similar to Minimise the absolute diff b/w
# the subset sums (DP). Think about it.
s=sum(stones)
n=len(stones)
dp=[[False for i in range(s+1)] for j in range(n+1)]
for i in range(n+1):
for j in range(s+1):
if(i==0):
dp[i][j]=False
if(j==0):
dp[i][j]=True
else:
if(stones[i-1]<=j):
inc=dp[i-1][j-stones[i-1]]
exc=dp[i-1][j]
dp[i][j]=(inc or exc)
else:
dp[i][j]=dp[i-1][j]
# print(dp[n])
ans=float('inf')
for j in range(s+1):
if(dp[n][j]==True):
ans=min(ans,abs(s-j-j))
return ans
Last updated