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
30 changes: 30 additions & 0 deletions DeleteAndEarn.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
class Solution {
public int deleteAndEarn(int[] nums) {
//TC - O(max(n , m)), where n is length of nums array, and m is the length of arr, which ever is greater
//SC - O(m), where m is the max element in the nums array

//iterate the nums array to find the maximum number in the array
int max = Integer.MIN_VALUE;
for (int num : nums) {
if (num > max) {
max = num;
}
}

//create an array of length equal to max so that we can store the total value of each number at their respective index
int[] arr = new int[max + 1];
for (int num : nums) {
arr[num] += num;
}

// iterate over this array and at each step calculate the max points between picking the cuu element or summing up prev and element at current index
int prev = arr[0];
int curr = Math.max(arr[0], arr[1]);
for (int i = 2; i < arr.length; i++) {
int temp = curr;
curr = Math.max(curr, arr[i] + prev);
prev = temp;
}
return curr;
}
}
39 changes: 39 additions & 0 deletions MinFallingPathSum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
class Solution {
public int minFallingPathSum(int[][] matrix) {
// TC = O(n^2)
// SC = O(n^2)
int n = matrix.length;
int m = matrix[0].length;
// create a 2d array to store the minimum path from that index, added one more row/column for ease of calculation
int dp[][] = new int[n + 1][m + 1];

if (n == 1) {
return matrix[0][0];
}

// iterating from the bottom of the array nnd keep finding minimum as we go up
for (int i = n-1; i >= 0; i--) {
for (int j = 0; j < m; j++) {
// if it is the first column, we only need to check j and j+1 to not go out of bounds
if (j == 0) {
dp[i][j] = Math.min(dp[i+1][j], dp[i+1][j+1]) + matrix[i][j];
} else if (j == m - 1) {
// if it is the last column, we only need to check j and j-1 to not go out of bounds
dp[i][j] = Math.min(dp[i+1][j], dp[i+1][j-1]) + matrix[i][j];
} else {
// otherwise check all 3 paths
dp[i][j] = Math.min(dp[i+1][j], Math.min(dp[i+1][j-1], dp[i+1][j+1])) + matrix[i][j];
}
}
}

int min = Integer.MAX_VALUE;
// traverse the first row of the array to find the minimum calculated path
for (int j = 0; j < m; j++) {
if (min > dp[0][j]) {
min = dp[0][j];
}
}
return min;
}
}