MEDIUM NC#102 Blind #23 Dynamic Programming 1D

213. House Robber II

๐Ÿ“– Problem

Houses are arranged in a circle (first and last are adjacent). Return the maximum amount of money you can rob without alerting the police.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing
  • โ€ขArray DP table updates
  • โ€ขState transition thinking
  • โ€ขBase case initialization

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation
  • โ€ขApply Dynamic Programming reasoning pattern
  • โ€ขApply Recursion reasoning pattern

๐Ÿ’ก Approach

  • โ†’ Two cases: rob houses 0 to n-2, or rob houses 1 to n-1
  • โ†’ Use same logic as House Robber I for each case
  • โ†’ Return max of both cases
  • โ†’ Time: O(n), Space: O(1)

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขTwo cases: rob houses 0 to n-2, or rob houses 1 to n-1
  • โ€ขUse same logic as House Robber I for each case
  • โ€ขReturn max of both cases

Common Pitfalls

  • โ€ขTime: O(n), Space: O(1)

๐Ÿงช Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
rob2([2,3,2]);
Expected:
3
Test Case 2
Not run
Input:
rob2([1,2,3,1]);
Expected:
4
Test Case 3
Not run
Input:
rob2([1,2,3]);
Expected:
3

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit