From d611bd9a84342839be4392bb5dd353421f2033c0 Mon Sep 17 00:00:00 2001 From: Ayush Chaudhary Date: Sun, 21 Jun 2026 17:27:36 -0500 Subject: [PATCH] Implement Min Falling Path Sum and Delete and Earn --- DeleteAndEarn.java | 37 +++++++++++++++++++++++++++++++++++++ MinFallingPathSum.java | 26 ++++++++++++++++++++++++++ Sample.java | 7 ------- 3 files changed, 63 insertions(+), 7 deletions(-) create mode 100644 DeleteAndEarn.java create mode 100644 MinFallingPathSum.java delete mode 100644 Sample.java diff --git a/DeleteAndEarn.java b/DeleteAndEarn.java new file mode 100644 index 00000000..4e5232c8 --- /dev/null +++ b/DeleteAndEarn.java @@ -0,0 +1,37 @@ +// Time Complexity : O(N+k) +// Space Complexity : o(N) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : No + + +// Your code here along with comments explaining your approach +// Find the maximum value in nums so we can create an array of size max + 1 +// arr[i] stores the total points earned by taking all occurrences of number i +// House Robber logic: prev represents the best answer up to i - 2 and curr represents the best answer up to i - 1 +class DeleteAndEarn{ + public int deleteAndEarn(int[] nums) { + + int max =Integer.MIN_VALUE; + for(int num : nums){ + max = Math.max(max, num); + } + + int []arr = new int[max+1]; + + for(int num : nums){ + arr[num] += num; + } + + int prev = arr[0]; + int curr = Math.max(prev, arr[1]); + + for(int i = 2; i < arr.length; i++){ + int temp = curr; + curr = Math.max(curr, prev+arr[i]); + prev= temp; + } + + return curr; + + } +} diff --git a/MinFallingPathSum.java b/MinFallingPathSum.java new file mode 100644 index 00000000..f696d619 --- /dev/null +++ b/MinFallingPathSum.java @@ -0,0 +1,26 @@ +class MinFallingPathSum { + public int minFallingPathSum(int[][] matrix) { + int dp[] = new int[matrix.length + 1]; + for (int row = matrix.length - 1; row >= 0; row--) { + int currentRow[] = new int[matrix.length + 1]; + for (int col = 0; col < matrix.length; col++) { + if (col == 0) { + currentRow[col] = + Math.min(dp[col], dp[col + 1]) + matrix[row][col]; + } else if (col == matrix.length - 1) { + currentRow[col] = + Math.min(dp[col], dp[col - 1]) + matrix[row][col]; + } else { + currentRow[col] = Math.min(dp[col], + Math.min(dp[col + 1], dp[col - 1])) + matrix[row][col]; + } + } + dp = currentRow; + } + int minFallingSum = Integer.MAX_VALUE; + for (int startCol = 0; startCol < matrix.length; startCol++) { + minFallingSum = Math.min(minFallingSum, dp[startCol]); + } + return minFallingSum; + } +} \ No newline at end of file diff --git a/Sample.java b/Sample.java deleted file mode 100644 index 1739a9cb..00000000 --- a/Sample.java +++ /dev/null @@ -1,7 +0,0 @@ -// Time Complexity : -// Space Complexity : -// Did this code successfully run on Leetcode : -// Any problem you faced while coding this : - - -// Your code here along with comments explaining your approach