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
58 changes: 58 additions & 0 deletions problem1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/**
Time Complexity : O(N + M)
Explanation:
- O(N) to build the frequency/points array
- O(M) to run DP where M = max value in nums

Space Complexity : O(M)
Explanation:
We use an array of size (max value + 1) for points and DP.

Did this code successfully run on LeetCode : Yes

Any problem you faced while coding this :
Initially tried solving directly on nums which became complex due to
delete constraints. Then converted the problem to House Robber:
- Picking number i → cannot pick i-1 and i+1
So created an array where:
arr[i] = total points from value i
and applied standard House Robber DP.
*/

class Solution {



public int deleteAndEarn(int[] nums) {

int max = Integer.MIN_VALUE;
int n = nums.length;

// Find max value
for (int i = 0; i < n; i++) {
max = Math.max(max, nums[i]);
}

// Build points array
int[] arr = new int[max + 1];
for (int i = 0; i < n; i++) {
arr[nums[i]] += nums[i];
}

int m = arr.length;

// Edge case
if (m == 1) return arr[0];

int[] dp = new int[m];
dp[0] = 0;
dp[1] = Math.max(arr[1], 0);

// House Robber DP
for (int i = 2; i < m; i++) {
dp[i] = Math.max(dp[i - 1], dp[i - 2] + arr[i]);
}

return dp[m - 1];
}
}
64 changes: 64 additions & 0 deletions problem2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
Time Complexity : O(N^2)
Explanation:
We fill an N x N DP table, processing each cell once.

Space Complexity : O(N^2)
Explanation:
DP table of size N x N is used.

Did this code successfully run on LeetCode : Yes

Any problem you faced while coding this :
Initially struggled with boundary conditions (first and last column).
Fixed it by handling:
- j == 0 → can only come from down or down-right
- j == n-1 → can only come from down or down-left
Also needed to correctly take minimum of all three possible directions.
*/


class Solution {


public int minFallingPathSum(int[][] matrix) {

int n = matrix.length;

int[][] dp = new int[n][n];
int min = Integer.MAX_VALUE;

// Base case: last row
for (int i = 0; i < n; i++) {
dp[n - 1][i] = matrix[n - 1][i];
}

// Fill DP from bottom to top
for (int i = n - 2; i >= 0; i--) {

for (int j = 0; j < n; j++) {

if (j == 0) {
dp[i][j] = matrix[i][j] +
Math.min(dp[i + 1][j], dp[i + 1][j + 1]);
}
else if (j == n - 1) {
dp[i][j] = matrix[i][j] +
Math.min(dp[i + 1][j], dp[i + 1][j - 1]);
}
else {
dp[i][j] = matrix[i][j] +
Math.min(dp[i + 1][j],
Math.min(dp[i + 1][j - 1], dp[i + 1][j + 1]));
}
}
}

// Find minimum in first row
for (int i = 0; i < n; i++) {
min = Math.min(min, dp[0][i]);
}

return min;
}
}