diff --git a/delete-and-earn.py b/delete-and-earn.py new file mode 100644 index 00000000..ab9d2baf --- /dev/null +++ b/delete-and-earn.py @@ -0,0 +1,17 @@ +# O(n) time, O(n) space +class Solution: + def deleteAndEarn(self, nums: List[int]) -> int: + + if not nums: + return 0 + + maxVal = max(nums) + t = [0]*(maxVal+1) + + for num in nums: + t[num]+=num + + for i in range(2,len(t)): + t[i]=max(t[i-1],t[i]+t[i-2]) + + return t[-1] \ No newline at end of file diff --git a/min-falling-path-sum.py b/min-falling-path-sum.py new file mode 100644 index 00000000..9a7027ed --- /dev/null +++ b/min-falling-path-sum.py @@ -0,0 +1,25 @@ +# time O(n*n), space O(n*n) +class Solution: + def minFallingPathSum(self, matrix: List[List[int]]) -> int: + n=len(matrix) + dp = [[0] * n for i in range(n)] + for i in range(n): + dp[0][i]=matrix[0][i] + + for i in range(1,n): + for j in range(n): + # first col - 2 val compare + if j==0: + dp[i][j]=matrix[i][j]+min(dp[i-1][j],dp[i-1][j+1]) + # last col - 2 val compare + elif j == n-1: + dp[i][j]=matrix[i][j]+min(dp[i-1][j],dp[i-1][j-1]) + # middle - compare all 3 + else: + dp[i][j]=matrix[i][j]+min(dp[i-1][j-1],dp[i-1][j],dp[i-1][j+1]) + + # return the min of the last row + res = dp[n-1][0] + for i in range(n): + res= min(dp[n-1][i],res) + return res \ No newline at end of file