diff --git a/house-robber-ii/yolophg.js b/house-robber-ii/yolophg.js new file mode 100644 index 000000000..90cb691db --- /dev/null +++ b/house-robber-ii/yolophg.js @@ -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); +}; diff --git a/house-robber/yolophg.js b/house-robber/yolophg.js new file mode 100644 index 000000000..4358792ac --- /dev/null +++ b/house-robber/yolophg.js @@ -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); +};