Skip to content
Open

DP-3 #1526

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions DeleteAndEarn.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Time Complexity : O(n + max(n))
# Space Complexity : O(max(n))
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : Store total points for each number and apple house robber style decision.

class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
max_val = max(nums)

arr = [0] * (max_val + 1)

for num in nums:
arr[num] += num


dp = [0] * (max_val + 1)

dp[0] = arr[0]
dp[1] = max(arr[0], arr[1])

for i in range(2, max_val + 1):
dp[i] = max(dp[i-1], dp[i-2] + arr[i])

return dp[max_val]


25 changes: 25 additions & 0 deletions MinFallingPathSum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Time Complexity : O(n^2)
# Space Complexity : O(n^2)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : Only when a new min appears, we store the previous min in the stack,
# so that when the current min is removed, we can restore the old one in constant time.

class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
n = len(matrix)
dp = [[0] * n for _ in range(n)]

for c in range(n):
dp[n - 1][c] = matrix[n - 1][c]

for r in range(n - 2, -1, -1):
for c in range(n):
if c == 0:
dp[r][c] = matrix[r][c] + min(dp[r+1][c], dp[r+1][c+1])
elif c == n-1:
dp[r][c] = matrix[r][c] + min(dp[r+1][c], dp[r+1][c-1])
else:
dp[r][c] = matrix[r][c] + min(dp[r+1][c], dp[r+1][c-1], dp[r+1][c+1])

return min(dp[0])