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
54 changes: 54 additions & 0 deletions leetcode_740.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 22 13:29:02 2026

@author: rishigoswamy

LeetCode 740: Delete and Earn
Link: https://leetcode.com/problems/delete-and-earn/

Approach:
Convert the problem into House Robber (LeetCode 198).

If we pick value x, we earn (x * freq[x]) points, but we lose the ability to pick
x-1 and x+1 (since they get deleted). That creates an "adjacent conflict" on the
value line: choosing x conflicts with choosing x-1 and x+1.

So we build an array points[] where:
points[x] = total points we can earn by taking all occurrences of value x

Then the problem becomes:
"Choose non-adjacent indices in points[] to maximize sum"
which is exactly House Robber.

// Time Complexity : O(n + maxVal)
n = len(nums), maxVal = max(nums)
- O(n) to build points array
- O(maxVal) for the DP pass
// Space Complexity : O(maxVal)
points array size is maxVal + 1

"""
from typing import List

class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
array = [0] * (max(nums)+1)

for num in nums:
array[num] += num

print(array)

del1 = 0
del2 = 0
for i in range(len(array)):

temp = max(array[i]+ del1, del2)
del1 = del2
del2 = temp
return del2



51 changes: 51 additions & 0 deletions leetcode_931.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 22 13:32:07 2026

@author: rishigoswamy

LeetCode 931: Minimum Falling Path Sum
Link: https://leetcode.com/problems/minimum-falling-path-sum/

Approach:
Dynamic Programming (row by row).

Let prev[j] = minimum falling path sum to reach column j in the previous row.
For the current row i and column j:
curr[j] = matrix[i][j] + min(prev[j], prev[j-1], prev[j+1])
(only include neighbors that are in bounds)

We only need the previous row to compute the current row, so we use O(n) extra space.

// Time Complexity : O(n^2)
n = number of rows = number of columns (square matrix)
Each cell computed once with O(1) work.
// Space Complexity : O(n)
prev and curr arrays of length n.

"""

from typing import List


class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
temp = []
prev = matrix[0]
for i in range(1, len(matrix)):
temp = []
temp.append(
matrix[i][0] +
min(prev[0], prev[1]))
for j in range(1, len(matrix) - 1):
temp.append(matrix[i][j]+ min(prev[j-1],
prev[j],
prev[j+1]))
temp.append(matrix[i][-1] + min(prev[-1], prev[-2]))
prev = temp
return min(prev)