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
29 changes: 29 additions & 0 deletions Problem1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Time Complexity : O(n + maxValue)
// Space Complexity : O(maxValue)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
class Solution {
public int deleteAndEarn(int[] nums) {
// Edge case
if (nums.length== 0) return 0;
int max=0;
for (int n:nums) {
max = Math.max(max, n);
}
// points[i] = total points we get if we take number i
int[] points = new int[max + 1];
for (int n : nums) {
points[n]=points[n]+n;
}
// Same as house robber
int prev2 = 0;// dp[i-2]
int prev1 = points[0]; // dp[i-1]
for (int i=1;i<= max;i++) {
int curr = Math.max(prev1,prev2+points[i]);
prev2=prev1;
prev1=curr;
}
return prev1;
}
}

29 changes: 29 additions & 0 deletions Problem2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Time Complexity : O(n*n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
class Solution {
public int minFallingPathSum(int[][] matrix) {
int n = matrix.length;
// Start from second row
for (int i=1;i<n;i++) {
for (int j=0;j<n;j++) {
// down(i+1,j)
// down-left(i+1,j-1)
// down-right(i+1,j+1)
int up=matrix[i-1][j];
int left=(j>0)?matrix[i-1][j-1]:Integer.MAX_VALUE;
int right =(j<n-1)?matrix[i-1][j+1]: Integer.MAX_VALUE;
// Add minimum of possible paths
matrix[i][j] += Math.min(up, Math.min(left, right));
}
}
// Answer is minimum in last row
int ans = Integer.MAX_VALUE;
for (int j=0; j<n;j++) {
ans=Math.min(ans,matrix[n - 1][j]);
}
return ans;
}
}