Completed DP-3 Assignment#1535
Conversation
Least Falling Path Sum (Minimum_Falling_Path_Sum.java)Your approach to use memoization is correct and improves the time complexity from exponential to polynomial. However, there are a few issues to address:
Suggested correction for the base cases: private int helper(int[][] matrix, int i, int j) {
int n = matrix.length;
// Check if j is out of bounds first
if (j < 0 || j >= n) {
return Integer.MAX_VALUE;
}
// Then check if we have reached the last row
if (i == n - 1) {
return matrix[i][j];
}
if (memo[i][j] != null) {
return memo[i][j];
}
int down = helper(matrix, i + 1, j);
int downLeft = helper(matrix, i + 1, j - 1);
int downRight = helper(matrix, i + 1, j + 1);
memo[i][j] = matrix[i][j] + Math.min(down, Math.min(downLeft, downRight));
return memo[i][j];
}Note: In the base case when Alternatively, you can keep the base case as Actually, the original reference solution has: if (j < 0 || j >= n) {
return Integer.MAX_VALUE;
}
if (i == n) {
return 0;
}This is correct. So your base case for if (j<0 || j>=n) return Integer.MAX_VALUE -10;
if (i==n) return 0;This is almost correct, but the value returned for out-of-bound should be Also, note that in the base case when So your base cases are almost correct, but the out-of-bound return value should be
VERDICT: NEEDS_IMPROVEMENT Delete and Earn (Delete_and_earn.java)Your solution is well-structured and follows the dynamic programming approach correctly. However, you need to handle the edge case where the maximum value in To fix this, you should check if Here's a corrected version: class Solution {
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;
}
if (max == 0) {
return arr[0];
}
int[] dp = new int[max + 1];
dp[0] = arr[0];
if (max == 1) {
return Math.max(arr[0], arr[1]);
}
dp[1] = Math.max(arr[0], arr[1]);
for (int i = 2; i <= max; i++) {
dp[i] = Math.max(dp[i - 1], arr[i] + dp[i - 2]);
}
return dp[max];
}
}Alternatively, you can use a more general approach without multiple conditionals by ensuring that the dp array is built only for indices that exist. Another common approach is to use a dp array that starts from index 0 and goes to max, and then handle the base cases within the loop by checking the index. Your code is almost correct, and with this small fix, it will handle all cases. Keep up the good work! VERDICT: NEEDS_IMPROVEMENT |
No description provided.