Skip to content

Commit

Permalink
Create 1049-last-stone-weight-ii.py
Browse files Browse the repository at this point in the history
  • Loading branch information
neetcode-gh authored Feb 18, 2023
1 parent c6de535 commit 57f4ad2
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions python/1049-last-stone-weight-ii.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class Solution:
def lastStoneWeightII(self, stones: List[int]) -> int:
# Memoization
stoneSum = sum(stones)
target = ceil(stoneSum / 2)

def dfs(i, total):
if total >= target or i == len(stones):
return abs(total - (stoneSum - total))
if (i, total) in dp:
return dp[(i, total)]

dp[(i, total)] = min(dfs(i + 1, total),
dfs(i + 1, total + stones[i]))
return dp[(i, total)]

dp = {}
return dfs(0, 0)

0 comments on commit 57f4ad2

Please sign in to comment.