AlgoInsight

DSA problem

House Robber II

Medium1-D DPPattern: 1-D DPtop75FreeAmazonMicrosoftGoogleMetaApple

You are a professional robber planning to rob houses along a street. This time the houses are arranged in a circle: that is, the first house is the neighbor of the last one. Adjacent houses still have connected security systems, so robbing two of them on the same night triggers the alarm. Given an integer array nums representing the money in each house, return the maximum amount of money you can rob without alerting the police.

The circular arrangement adds a single extra constraint over House Robber I: houses 0 and n - 1 are now adjacent, so they can't both be robbed. Every other rule and every other piece of intuition carries over unchanged.

The clean reduction is to split the problem into two linear sub-problems and take the better outcome. Either the robber skips house n - 1 and considers nums[0 .. n - 2], or the robber skips house 0 and considers nums[1 .. n - 1]. The first scenario removes the circular conflict involving the last house, the second removes it for the first house, and any valid circular plan falls into one of the two — never both at once.

For each linear sub-array we apply the standard House Robber I bottom-up DP with two rolling variables: dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]). The final answer is the maximum of the two sub-solutions, computed in O(n) time and O(1) extra space.

Examples

Example 1
Input: nums = [2,3,2]
Output: 3
Explanation: You cannot rob houses 0 and 2 because they are circular neighbors, so the best is to rob house 1 for 3.
Example 2
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob houses 0 and 2 (1 + 3 = 4), or houses 1 and 3 (2 + 1 = 3). The maximum is 4.
Example 3
Input: nums = [1,2,3]
Output: 3
Explanation: Any pair of houses are now neighbors (circular), so rob only the largest one.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

dp1d-dparray

Browse all DSA problems