Skip to content

Commit 2cd3f4d

Browse files
committed
Add week 10 solutions: houseRobber1, 2
1 parent a2c22bf commit 2cd3f4d

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

house-robber-ii/yolophg.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Time Complexity: O(n)
2+
// Space Complexity: O(n)
3+
4+
var rob = function (nums) {
5+
// to rob a linear list of houses
6+
function robLinear(houses) {
7+
let prev1 = 0;
8+
let prev2 = 0;
9+
10+
for (let money of houses) {
11+
let temp = Math.max(prev1, money + prev2);
12+
prev2 = prev1;
13+
prev1 = temp;
14+
}
15+
16+
return prev1;
17+
}
18+
19+
// 1. excluding the last house (rob from first to second-to-last)
20+
// 2. excluding the first house (rob from second to last)
21+
let robFirstToSecondLast = robLinear(nums.slice(0, -1));
22+
let robSecondToLast = robLinear(nums.slice(1));
23+
24+
// return the maximum money
25+
return Math.max(robFirstToSecondLast, robSecondToLast);
26+
};

house-robber/yolophg.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Time Complexity: O(n)
2+
// Space Complexity: O(n)
3+
4+
var rob = function (nums) {
5+
// to store the maximum money that can be robbed up to each house
6+
let memo = new Array(nums.length).fill(-1);
7+
8+
function robFrom(i) {
9+
// if the index is out of bounds, return 0
10+
if (i >= nums.length) return 0;
11+
12+
// 1. rob this house and move to the house two steps ahead
13+
// 2. skip this house and move to the next house
14+
// take the maximum of these two choices
15+
let result = Math.max(nums[i] + robFrom(i + 2), robFrom(i + 1));
16+
17+
// store the result
18+
memo[i] = result;
19+
20+
return result;
21+
}
22+
23+
// start robbing from the first house
24+
return robFrom(0);
25+
};

0 commit comments

Comments
 (0)