diff --git a/OJ notes/pages/Leetcode House-Robber.md b/OJ notes/pages/Leetcode House-Robber.md index cac63e5..2bfde04 100644 --- a/OJ notes/pages/Leetcode House-Robber.md +++ b/OJ notes/pages/Leetcode House-Robber.md @@ -145,3 +145,39 @@ public: ```cpp +``` + +#### Stage 4: + +```cpp +class Solution { +public: + int rob(vector &nums) { + // iterative, from the buttom up + // We can utilize the hash map feature + + int size = nums.size(); + if (size == 0) { + return 0; + } else if (size == 1) { + return nums[0]; + } + + int prev1, prev2, next; // next: i + 1 + + int curLoc = 1; + prev1 = nums[0]; // i - 1 + prev2 = max(nums[0], nums[1]); // i + next = prev2; + while (curLoc < size - 1) { + // cache[curLoc + 1] = max(cache[curLoc - 1] + nums[curLoc + 1] , + // cache[curLoc]); + next = max(prev1 + nums[curLoc + 1], prev2); + prev1 = prev2; + prev2 = next; + curLoc++; + } + return next; + } +}; +``` \ No newline at end of file