LeetCode 213: House Robber II Solution

Master LeetCode problem 213 (House Robber II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

213. House Robber II

Problem Explanation

Explanation:

To solve this problem, we can break it down into two subproblems:

  1. Rob houses from the first house to the second-to-last house.
  2. Rob houses from the second house to the last house.

We can then apply the House Robber algorithm to each subproblem and return the maximum value obtained from these two solutions.

:

Solution Code

class Solution {
    public int rob(int[] nums) {
        if (nums.length == 1) {
            return nums[0];
        }
        return Math.max(robHelper(nums, 0, nums.length - 2), robHelper(nums, 1, nums.length - 1));
    }
    
    private int robHelper(int[] nums, int start, int end) {
        int prev1 = 0, prev2 = 0;
        for (int i = start; i <= end; i++) {
            int temp = prev1;
            prev1 = Math.max(prev2 + nums[i], prev1);
            prev2 = temp;
        }
        return prev1;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 213 (House Robber II)?

This page provides optimized solutions for LeetCode problem 213 (House Robber II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 213 (House Robber II)?

The time complexity for LeetCode 213 (House Robber II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 213 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 213 in Java, C++, or Python.

Back to LeetCode Solutions