Skip to content

Commit

Permalink
Add week 10 solutions: houseRobber1, 2
Browse files Browse the repository at this point in the history
  • Loading branch information
yolophg committed Jul 6, 2024
1 parent a2c22bf commit 2cd3f4d
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
26 changes: 26 additions & 0 deletions house-robber-ii/yolophg.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Time Complexity: O(n)
// Space Complexity: O(n)

var rob = function (nums) {
// to rob a linear list of houses
function robLinear(houses) {
let prev1 = 0;
let prev2 = 0;

for (let money of houses) {
let temp = Math.max(prev1, money + prev2);
prev2 = prev1;
prev1 = temp;
}

return prev1;
}

// 1. excluding the last house (rob from first to second-to-last)
// 2. excluding the first house (rob from second to last)
let robFirstToSecondLast = robLinear(nums.slice(0, -1));
let robSecondToLast = robLinear(nums.slice(1));

// return the maximum money
return Math.max(robFirstToSecondLast, robSecondToLast);
};
25 changes: 25 additions & 0 deletions house-robber/yolophg.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Time Complexity: O(n)
// Space Complexity: O(n)

var rob = function (nums) {
// to store the maximum money that can be robbed up to each house
let memo = new Array(nums.length).fill(-1);

function robFrom(i) {
// if the index is out of bounds, return 0
if (i >= nums.length) return 0;

// 1. rob this house and move to the house two steps ahead
// 2. skip this house and move to the next house
// take the maximum of these two choices
let result = Math.max(nums[i] + robFrom(i + 2), robFrom(i + 1));

// store the result
memo[i] = result;

return result;
}

// start robbing from the first house
return robFrom(0);
};

0 comments on commit 2cd3f4d

Please sign in to comment.