From 851403b7367ae7f93c67ca71d9021e0be4a47154 Mon Sep 17 00:00:00 2001 From: Kartavya Bhatt Date: Sat, 27 Jun 2026 14:31:00 -0400 Subject: [PATCH] DP-3 complete --- Problem1.py | 31 +++++++++++++++++++++++++++++++ Problem2.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 Problem1.py create mode 100644 Problem2.py diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..5b3d70cb --- /dev/null +++ b/Problem1.py @@ -0,0 +1,31 @@ +''' +This is same as house robber problem with the added condition that if the previous number is same +as current number-1 then do not choose it previous number. + +Else choose the max between both the conditions. +Time Complexity: O(n) +Space Complexity: O(n) +''' + +class Solution: + def deleteAndEarn(self, nums: List[int]) -> int: + numSum = {} + for num in nums: + if num in numSum: + numSum[num] += num + else: + numSum[num] = num + + sortedKeys = sorted(numSum.keys()) + choose, notChoose = numSum[sortedKeys[0]], 0 + prev = sortedKeys[0] + for num in sortedKeys[1:]: + if prev == num-1: + chooseNum = numSum[num] + notChoose + else: + chooseNum = numSum[num] + max(choose, notChoose) + notChooseNum = max(choose, notChoose) + choose, notChoose = chooseNum, notChooseNum + prev = num + + return max(choose, notChoose) \ No newline at end of file diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..c016c68e --- /dev/null +++ b/Problem2.py @@ -0,0 +1,28 @@ +''' +The brute force solution is to traverse the gird from top to bottom resurcively and +choose the minimum sum from the 3 paths from a given cell. The time complexity will be +O(3^n) and Space complexity will be O(n*m) where n is the total number of rows and m +is total number of columns. + +This can be optimized by doing a top-bottom approach and use the intuition that the +best path to reach to the cell is the minimum of the 3 paths from above. + +Time complexity: O(n*m) +Space complexity: O(m) +''' +class Solution: + def minFallingPathSum(self, matrix: List[List[int]]) -> int: + rows = len(matrix) + cols = len(matrix[0]) + for i in range(1,rows): + for j in range(cols): + if j == 0: + matrix[i][j] += min(matrix[i-1][j], matrix[i-1][j+1]) + + elif j == cols-1: + matrix[i][j] += min(matrix[i-1][j-1], matrix[i-1][j]) + + else: + matrix[i][j] += min(matrix[i-1][j-1], matrix[i-1][j], matrix[i-1][j+1]) + + return min(matrix[-1])