House Robber - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

  • Intuition:
    We cannot rob two adjacent houses, so for each house we decide whether to rob it or skip it based on which choice yields a higher total. This leads to a simple recurrence: at every step, our best total depends only on the results of the last two evaluated houses.
  • State Representation:
    Instead of keeping a full DP array, we only need two running values:
    • prevMax — maximum money robbed so far excluding the last evaluated house.
    • currMax — maximum money robbed so far (including all evaluated houses up to this point).
  • Transition:
    For each house with value currentHouseValue:
    • If we rob this house, we must skip the last evaluated one to avoid triggering the alarm. Therefore, the best total in this case is the money robbed up to the house before the last one (prevMax) plus the value of the current house: prevMax + currentHouseValue.
    • If we skip this house, we simply carry forward the best total so far, which is currMax.
    • The optimal total for the current house is the maximum of these two choices: newMax = max(currMax, prevMax + currentHouseValue).
  • State Update:
    After each house:
    • prevMax = currMax
    • currMax = newMax
    This effectively moves the window forward by one house while keeping only the last two states in memory.
  • Termination:
    After processing all houses, currMax holds the maximum amount of money that can be robbed without alerting the police.

Time Complexity

We iterate through each house exactly once, performing a constant amount of work per iteration (a few arithmetic operations and comparisons). Therefore, the overall time complexity is O(n), where n is the number of houses.

Space Complexity

We only keep track of two variables — prevMax and currMax — regardless of how many houses there are. Since no additional data structures grow with input size, the space complexity is O(1).

Visucodize editorial solution titled JS Solution for LeetCode's House Robber coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/house-robber.