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
65 changes: 65 additions & 0 deletions deleteAndEarn.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
* @param {number[]} nums
* @return {number}
Intuition:
* Convert the problem into a value-based array where each index stores total points earned by taking that number.
* At each index, decide between **skipping it** or **taking it and skipping the next adjacent value**.
* Use DFS + memoization to avoid recomputing states, effectively turning it into a House Robber–style DP.
T.C: O(n+k)
S.C: O(k)
*/
var deleteAndEarn = function (nums) {

let maxLength = Math.max(...nums);
let dp = new Array(maxLength + 1).fill(0);
let memo = [];

for (let i = 0; i < nums.length; i++) {
let currNum = nums[i];
dp[currNum] += currNum;
}

const dfs = (idx) => {
// base case
if (idx > maxLength) return 0;

if (memo[idx]) return memo[idx];
// action
// 0
let zero = dfs(idx + 1);
// 1
let one = dp[idx] + dfs(idx + 2);
memo[idx] = Math.max(zero, one);
return memo[idx];
};

return dfs(0);
};


/**
* @param {number[]} nums
* @return {number}
* Intuition:
Convert values into a dp array where each index holds total points for that number.
For each number i, choose between taking it (add dp[i-2]) or skipping it (keep dp[i-1]).
This mirrors the House Robber pattern: avoid adjacent values while maximizing total points.
T.C: O(n+k)
S.C: O(k)
*/
var deleteAndEarn = function(nums) {

let maxLength = Math.max(...nums);
let dp = new Array(maxLength+1).fill(0);

for(let i = 0; i<nums.length;i++){
let currNum = nums[i];
dp[currNum] += currNum;
}

for(let i = 2; i<dp.length; i++){
dp[i] = Math.max(dp[i]+dp[i-2], dp[i-1]);
}

return dp[maxLength];
};
31 changes: 31 additions & 0 deletions minFallingPathSum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* @param {number[][]} matrix
* @return {number}
* Intuition:
For each cell, the minimum path sum to reach it depends only on the three possible cells from the previous row: top, top-left, and top-right.
We keep a dp array that stores the minimum falling path sums for the previous row, and build the current row using those values.
By updating row by row, we avoid extra 2D space and finally return the minimum value from the last row.
T.C: O(m*n)
S.C: O(m)
*/
var minFallingPathSum = function (matrix) {
let n = matrix.length;
let m = matrix[0].length;
let dp = [...matrix[0]];
for (let i = 1; i < n; i++) {
let newDp = new Array(m).fill(0);
for (let j = 0; j < m; j++) {
let minAbove = dp[j];
if (j > 0) {
minAbove = Math.min(minAbove, dp[j - 1]);
}
if (j < m - 1) {
minAbove = Math.min(minAbove, dp[j + 1]);
}

newDp[j] = matrix[i][j] + minAbove;
}
dp = newDp;
}
return Math.min(...dp)
};