From a3fed7f1687fac9f5cf037480af29994365a14f1 Mon Sep 17 00:00:00 2001 From: Shinjanee Gupta Date: Tue, 17 Feb 2026 11:50:31 -0800 Subject: [PATCH] DP-3 --- DeleteAndEarn.py | 27 +++++++++++++++++++++++++++ MinFallingPathSum.py | 25 +++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 DeleteAndEarn.py create mode 100644 MinFallingPathSum.py diff --git a/DeleteAndEarn.py b/DeleteAndEarn.py new file mode 100644 index 00000000..d6507821 --- /dev/null +++ b/DeleteAndEarn.py @@ -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] + + diff --git a/MinFallingPathSum.py b/MinFallingPathSum.py new file mode 100644 index 00000000..8bac902c --- /dev/null +++ b/MinFallingPathSum.py @@ -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]) \ No newline at end of file