Skip to content

Commit ddb836b

Browse files
committed
Add house-robber-ii solution
1 parent 17f64d9 commit ddb836b

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

house-robber-ii/Jeehay28.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// ✅ Time Complexity: O(n)
2+
// ✅ Space Complexity: O(1)
3+
4+
/**
5+
* @param {number[]} nums
6+
* @return {number}
7+
*/
8+
var rob = function (nums) {
9+
// Edge case: If there's only one house, return its value
10+
if (nums.length === 1) return nums[0];
11+
12+
// helper function
13+
const robHouses = (start, end) => {
14+
// prev1: stores the maximum money robbed up to the previous house.
15+
// prev2: stores the maximum money robbed up to the house before the previous house.
16+
let prev1 = 0,
17+
prev2 = 0;
18+
19+
for (let i = start; i <= end; i++) {
20+
let temp = Math.max(prev1, prev2 + nums[i]);
21+
22+
prev2 = prev1;
23+
24+
prev1 = temp;
25+
}
26+
27+
return prev1;
28+
};
29+
30+
// Excluding the last house: robHouses(0, nums.length - 2)
31+
// Excluding the first house: robHouses(1, nums.length - 1)
32+
33+
return Math.max(robHouses(0, nums.length - 2), robHouses(1, nums.length - 1));
34+
};
35+

0 commit comments

Comments
 (0)