diff --git a/deleteearn.java b/deleteearn.java new file mode 100644 index 00000000..6094f9dd --- /dev/null +++ b/deleteearn.java @@ -0,0 +1,35 @@ +// Time Complexity :O(m*n) +// Space Complexity :O(m*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: DP to solve using helper function to find max money we can earn by deleting and earning points from the array. We use memoization to store the results of subproblems to avoid redundant calculations. +class Solution { + Integer[] memo; + public int deleteAndEarn(int[] nums) { + int max = 0; + for (int num : nums) { + max = Math.max(max, num); + } + + int[] arr = new int[max + 1]; + for (int num : nums) { + arr[num] += num; + } + + this.memo = new Integer[max + 1]; + return helper(arr, 0); + } + + private int helper(int[] arr, int i) { + if (i >= arr.length) return 0; + if (memo[i] != null) return memo[i]; + + int case0 = helper(arr, i + 1); + int case1 = arr[i] + helper(arr, i + 2); + + memo[i] = Math.max(case0, case1); + return memo[i]; + } +} diff --git a/minpath.java b/minpath.java new file mode 100644 index 00000000..a810df8e --- /dev/null +++ b/minpath.java @@ -0,0 +1,35 @@ +// Time Complexity : O(n^2) +// Space Complexity : O(1) +// 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: DP to find min falling path sum. start from the second row and update each cell with the minimum path sum to reach that cell from the row above. Finally, return the minimum value from the last row. +class Solution { + public int minFallingPathSum(int[][] matrix) { + int n = matrix.length; + + for (int r = 1; r < n; r++) { + for (int c = 0; c < n; c++) { + + int minAbove = matrix[r - 1][c]; + + if (c > 0) { + minAbove = Math.min(minAbove, matrix[r - 1][c - 1]); + } + + if (c < n - 1) { + minAbove = Math.min(minAbove, matrix[r - 1][c + 1]); + } + + matrix[r][c] += minAbove; + } + } + + int minPathSum = Integer.MAX_VALUE; + for (int val : matrix[n - 1]) { + minPathSum = Math.min(minPathSum, val); + } + + return minPathSum; + } +} \ No newline at end of file