diff --git a/DeleteAndEarn.java b/DeleteAndEarn.java new file mode 100644 index 00000000..3bc953b9 --- /dev/null +++ b/DeleteAndEarn.java @@ -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]; + } +} \ No newline at end of file diff --git a/MinFallingSum.java b/MinFallingSum.java new file mode 100644 index 00000000..82c11701 --- /dev/null +++ b/MinFallingSum.java @@ -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