From 23598ee3b85bc883b881586ae6b0e90bb4b5275b Mon Sep 17 00:00:00 2001 From: Sanjoli Date: Sat, 13 Jun 2026 16:14:30 -0500 Subject: [PATCH] completed DP 2 course --- DeleteAndEarn.java | 30 ++++++++++++++++++++++++++++++ MinFallingPathSum.java | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 DeleteAndEarn.java create mode 100644 MinFallingPathSum.java diff --git a/DeleteAndEarn.java b/DeleteAndEarn.java new file mode 100644 index 00000000..c6f2301f --- /dev/null +++ b/DeleteAndEarn.java @@ -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; + } +} \ No newline at end of file diff --git a/MinFallingPathSum.java b/MinFallingPathSum.java new file mode 100644 index 00000000..64f72440 --- /dev/null +++ b/MinFallingPathSum.java @@ -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; + } +} \ No newline at end of file