Skip to content
Open

DP-3 #1536

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
55 changes: 55 additions & 0 deletions Minimum Falling Path Sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Time Complexity --> O(n*n) where n*n are the dimensions of matrix
# Space Complexity --> O(n)
class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
n = len(matrix)
if n==1:
return matrix[0][0]

dp = [0 for i in range(n)]
for i in range(n):
left = 0
for j in range(n):
temp = dp[j]
if j==0:
dp[j] = matrix[i][j] + min(dp[j], dp[j+1])
elif j==n-1:
dp[j] = matrix[i][j] + min(left, dp[j])
else:
dp[j] = matrix[i][j] + min(left, dp[j], dp[j+1])
left = temp

return min(dp)



'''
# Time Complexity --> O(n*n) where n*n are the dimensions of matrix
# Space Complexity --> O(n*n)
class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:

re = float('inf')
n = len(matrix)
self.memo = [[float('inf')]*(n) for i in range(n)]
for i in range(n):
re = min(re, self.helper(matrix, 0, i))
return re


def helper(self, matrix, row, col):
# base
if row==len(matrix):
return 0
if self.memo[row][col]!=float('inf'):
return self.memo[row][col]
# logic
if col==0:
case = matrix[row][col] + min(self.helper(matrix, row+1, col), self.helper(matrix, row+1, col+1))
elif col==len(matrix)-1:
case = matrix[row][col] + min(self.helper(matrix, row+1, col-1), self.helper(matrix, row+1, col))
else:
case = matrix[row][col]+min(self.helper(matrix, row+1, col-1), self.helper(matrix, row+1, col), self.helper(matrix, row+1, col+1))
self.memo[row][col] = case
return case
'''
14 changes: 14 additions & 0 deletions delete and earn.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Time Complexity --> O(n) where n is the max value available in the input list
# Space Complexity --> O(n)
# Approach --> creating an array where the indices would represent the number available in nums list. The values would be the sum of all its occurrences
class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
arr = [0]*(max(nums)+1)
for i in range(len(nums)):
arr[nums[i]] = arr[nums[i]]+nums[i]


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