Skip to content
Open
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
31 changes: 31 additions & 0 deletions Problem1.py
Original file line number Diff line number Diff line change
@@ -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)
28 changes: 28 additions & 0 deletions Problem2.py
Original file line number Diff line number Diff line change
@@ -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])