-
Notifications
You must be signed in to change notification settings - Fork 125
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add week 10 solutions: houseRobber1, 2
- Loading branch information
Showing
2 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}; |