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
29 changes: 29 additions & 0 deletions DeleteAndEarn.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Time complexity : Max (O(n), O(m)) n is size of input array and m is max value in input array
// Space Complexity: O(m) m is max value in input array
// We can change this problem to look like the 'House Robber' game. Choosing a number means
// we cannot choose its neighbors. First, we add up the total points for each number.
// Then, we look at each number one by one to find the highest score

class DeleteAndEarn {
public int deleteAndEarn(int[] nums) {
// find the max value in the array
int maxValue = Integer.MIN_VALUE;
for(int num : nums){
maxValue = Math.max(maxValue, num);
}
// create an array of length maxvalue
int[] array = new int[maxValue+1];
for( int num : nums) {
array[num] = array[num] + num;
}
// create a dp array
int[] dp = new int[maxValue+1];
dp[0] = array[0];
dp[1] = Math.max(array[0],array[1]);

for(int i=2; i< array.length; i++) {
dp[i] = Math.max(dp[i-1], dp[i-2]+array[i]);
}
return dp[maxValue];
}
}
36 changes: 36 additions & 0 deletions MinFallingSum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Time complexity : O(n^2)
// Space Complexity: O(n^2)
// We start by filling the last row of DP array with the last row of matrix where dp[i][j]
// is the minimum sum path until then.
class MinFallingSum {
public int minFallingPathSum(int[][] matrix) {
int m = matrix.length;
int n= matrix[0].length;
int[][] dp = new int[m][n];

// fill the dp array with the last row of the matrix
for(int i = 0; i < n; i++ ) {
dp[m-1][i] = matrix[m-1][i];
}

// calculate the min sum
for(int i = m-2; i>=0; i--){
for(int j=0; j<n; j++) {
if(j==0){
dp[i][j] = matrix[i][j] + Math.min(dp[i+1][j], dp[i+1][j+1]);
} else if (j == n-1) {
dp[i][j] = matrix[i][j] + Math.min(dp[i+1][j], dp[i+1][j-1]);
} else{
dp[i][j] = matrix[i][j] + Math.min(dp[i+1][j],Math.min(dp[i+1][j-1], dp[i+1][j+1]));
}
}
}

int minValue = Integer.MAX_VALUE;
for(int i = 0; i < n; i++ ) {
minValue = Math.min(minValue, dp[0][i]);
}

return minValue;
}
}