Algo-Sim › Dynamic Programming

House Robber II

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

Houses form a circle, so the first and last are neighbours: run House Robber without the last house and without the first, and keep the better.

Problem

As in House Robber, you cannot rob two adjacent houses, but now the houses stand in a circle, so the first and the last house are neighbours too. Return the most money you can take.

Constraints

Edge cases to test

Follow-up questions

Why do two linear runs suffice?
The first and last house can’t both be robbed, so one of them is excluded in every valid plan: O(n), O(1).
What if you also need the houses themselves?
Store choices per index in the winning run and walk back.

Solution

Java

public int rob(int[] nums) {
    if (nums.length == 1) return nums[0];
    return Math.max(robLine(nums, 0, nums.length - 2),
                    robLine(nums, 1, nums.length - 1));
}

private int robLine(int[] nums, int lo, int hi) {
    int prev = 0, curr = 0;
    for (int i = lo; i <= hi; i++) {
        int next = Math.max(curr, prev + nums[i]);
        prev = curr;
        curr = next;
    }
    return curr;
}

Python

def rob(nums):
    if len(nums) == 1:
        return nums[0]
    return max(rob_line(nums, 0, len(nums) - 2),
               rob_line(nums, 1, len(nums) - 1))


def rob_line(nums, lo, hi):
    prev = curr = 0
    for i in range(lo, hi + 1):
        prev, curr = curr, max(curr, prev + nums[i])
    return curr

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int rob(vector<int> &nums) {
        if (int(nums.size()) == 1)
            return nums[0];
        return std::max(robLine(nums, 0, int(nums.size()) - 2),
                        robLine(nums, 1, int(nums.size()) - 1));
    }

    int robLine(vector<int> &nums, int lo, int hi) {
        int prev = 0, curr = 0;
        for (int i = lo; i <= hi; i++) {
            int next = std::max(curr, prev + nums[i]);
            prev = curr;
            curr = next;
        }
        return curr;
    }
};

More Dynamic Programming problems