From 396465841fb6aa87b98930c715fabb389bd5bbad Mon Sep 17 00:00:00 2001 From: pranjay01 Date: Thu, 26 Feb 2026 23:31:41 -0800 Subject: [PATCH] Done DP-3 --- Problem1.py | 25 +++++++++++++++++++++++++ Problem2.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 53 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..adb262fb --- /dev/null +++ b/Problem1.py @@ -0,0 +1,25 @@ +#Delete and Earn + +#time complexity -> On +# space complexity -> On +import math +class Solution: + def deleteAndEarn(self, nums: List[int]) -> int: + if len(nums) == 1: + return nums[0] + # We'll have to convert the given array to house robber pattern + # get the array of length 10^4 as that is the max number possible + numsArr = [0] * 10001 + maxNum = 0 + minNum = math.inf + + for num in nums: + maxNum = max(maxNum,num) + minNum = min(minNum,num) + numsArr[num] +=num + + #Now use houseroober method, i.e for each index try to maximise the sum + numsArr[minNum+1] = max(numsArr[minNum], numsArr[minNum+1]) + for i in range(minNum+2,maxNum+1): + numsArr[i] = max(numsArr[i-1],(numsArr[i]+numsArr[i-2])) + return numsArr[maxNum] \ No newline at end of file diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..6a32eb70 --- /dev/null +++ b/Problem2.py @@ -0,0 +1,28 @@ +#Minimum Falling Path Sum + +#Time complexity O(mxn) +#Space complexity O(m) where m is the number of columns in the matrix +#The idea is to calculate for each index starting from row 2 what's the minimum sum we can achieve in that index. to minimise the sum at each index the logic will be +# sum of price at that index and the minimimum of the three/two from the top row. Dependinging if it's a middle index or at the edges of the matrix +#This will give the minimum sum at each index that is possible. In the end we'll just find in all the index which has the minimimu sum and return that +class Solution: + def minFallingPathSum(self, matrix: List[List[int]]) -> int: + columns = len(matrix[0]) + rows = len(matrix) + psblValuesAtEachColumn = [0]*columns + for j in range(0,columns): + psblValuesAtEachColumn[j] = matrix[0][j] + + for i in range (1, rows): + previousTopVal = None + for j in range(0,columns): + currentTopVal = psblValuesAtEachColumn[j] + if previousTopVal == None: + psblValuesAtEachColumn[j] = matrix[i][j] + min(psblValuesAtEachColumn[j],psblValuesAtEachColumn[j+1]) + previousTopVal = currentTopVal + elif j==columns-1: + psblValuesAtEachColumn[j] = matrix[i][j] + min(previousTopVal, psblValuesAtEachColumn[j]) + else: + psblValuesAtEachColumn[j] = matrix[i][j] + min(previousTopVal, psblValuesAtEachColumn[j],psblValuesAtEachColumn[j+1]) + previousTopVal = currentTopVal + return min(psblValuesAtEachColumn) \ No newline at end of file