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
35 changes: 35 additions & 0 deletions deleteearn.java
Original file line number Diff line number Diff line change
@@ -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];
}
}
35 changes: 35 additions & 0 deletions minpath.java
Original file line number Diff line number Diff line change
@@ -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;
}
}