๐Ÿ—“๏ธ Day 20: House Robber II (Circular Houses)

๐Ÿ“˜ What Youโ€™ll Learn

  • How House Robber II differs from the original
  • Why circular houses complicate things
  • How to split the problem into two subproblems
  • Implementing two DP runs to solve the problem
  • Optimizing in TypeScript
  • Real LeetCode example

๐Ÿง  Concept

Welcome to the circular version of the house robbing problem! ๐Ÿ ๐ŸŒ€

Youโ€™re still a professional robber, but now the houses are arranged in a circle โ€” meaning the first and last houses are neighbors! ๐Ÿ˜ฑ

You canโ€™t rob both the first and the last house. So, you split the problem into two linear DP runs:

  • Rob from house 0 to n-2
  • Rob from house 1 to n-1

Then, return the max of those two results.


๐Ÿ“Š Visualization

Given:

Index:   0   1   2   3   4
Money:  2   3   2   5   1

Because it's circular, you have to:

  • Either rob houses 0 to 3
  • Or rob houses 1 to 4

Run the standard House Robber DP on both ranges and take the best.


๐Ÿ’ป TypeScript Example

function rob(nums: number[]): number {
  if (nums.length === 0) return 0;
  if (nums.length === 1) return nums[0];

  function robLinear(arr: number[]): number {
    let prev1 = 0, prev2 = 0;
    for (let num of arr) {
      const temp = Math.max(prev1, prev2 + num);
      prev2 = prev1;
      prev1 = temp;
    }
    return prev1;
  }

  const excludeLast = robLinear(nums.slice(0, nums.length - 1));
  const excludeFirst = robLinear(nums.slice(1));

  return Math.max(excludeLast, excludeFirst);
}
  • โฑ๏ธ Time: O(n)
  • ๐Ÿ’พ Space: O(1)

๐Ÿงช LeetCode Homework

๐Ÿ“˜ 213. House Robber II

Youโ€™re a pro robber with circular house targets. Return the max amount of money you can rob without hitting two adjacent houses in a circle.

const houses = [2,3,2];
console.log(rob(houses)); // 3

const houses2 = [1,2,3,1];
console.log(rob(houses2)); // 4

๐Ÿ“Œ Key Takeaways

  • Circular houses = you canโ€™t rob first and last
  • Solve two linear rob problems and take the best result
  • Reuse your linear House Robber DP helper
  • This technique is useful for other "circular" array problems!

๐Ÿ”ฎ Up Next

โ–ถ๏ธ Day 21: Climbing Stairs Variants

This page was last edited on 2025-08-01 08:52

Powered by Wiki|Docs

This page was last edited on 2025-08-01 08:52

Tri Nguyen
No Copyright

Powered by Wiki|Docs