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
45 changes: 45 additions & 0 deletions coinChange.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* @param {number[]} coins
* @param {number} amount
* @return {number}

Intuition:

I am using dynamic programming with tabulation.

The DP table dp[i][j] represents the minimum number of coins needed to make amount j using the first i coin denominations.

I initialize dp[0][0] to handle the base case, since zero coins are needed to make amount zero, and all other values in the first row are set to infinity because no amount greater than zero can be formed without any coins.

If the current coin denomination is greater than the current amount, I copy the value from the previous row (dp[i-1][j]) because the coin cannot be used.

Otherwise, I take the minimum of not using the coin (dp[i-1][j]) and using the coin at least once (1 + dp[i][j - coin]), since coins can be used an unlimited number of times.
*/

// Tabulation
var coinChange = function (coins, amount) {
const m = coins.length;
const n = amount;
// m + 1 to accomadate 0 row
const dp = Array.from({
length: m + 1
}, () => []);
// base case
dp[0][0] = 0;
// initialize the first row with infinity
for (let i = 1; i <= n; i++) {
dp[0][i] = Infinity - 100;
}

for (let i = 1; i <= m; i++) {
for (let j = 0; j <= n; j++) {
if (j < coins[i - 1]) {
dp[i][j] = dp[i - 1][j];
} else {
dp[i][j] = Math.min(dp[i - 1][j], 1 + dp[i][j - coins[i - 1]]);
}
}
}

return dp[m][n] >= Infinity ? -1 : dp[m][n];
};
38 changes: 38 additions & 0 deletions houseOfRobbers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* @param {number[]} nums
* @return {number}
*/
// var rob = function(nums) {

// const robHelper = (idx) => {
// // base case
// if(idx >= nums.length) return 0;

// const zero = robHelper(idx+1);
// const one = nums[idx] + robHelper(idx+2);
// return Math.max(zero, one);
// } ;

// return robHelper(0);
// };

/**

Intuition:
**Intuition:**
The recursive solution caused time limit issues due to overlapping subproblems, so I converted it into a dynamic programming (tabulation) approach. At each index, the maximum profit is either skipping the current house (`dp[i - 1]`) or robbing it and adding its value to the profit from two houses back (`nums[i] + dp[i - 2]`). Thus:

`dp[i] = Math.max(dp[i - 1], nums[i] + dp[i - 2])`

**Time Complexity:** `O(n)`
**Space Complexity:** `O(n)`
*/
var rob = function (nums) {
// base case
if (nums.length === 1) return nums[0];
const dp = [nums[0], Math.max(nums[0], nums[1])];
for (let i = 2; i < nums.length; i++) {
dp[i] = Math.max(dp[i - 1], nums[i] + dp[i - 2]);
}
return dp[nums.length - 1];
};