House Robber II in Python and Java
In this tutorial, we will learn LeetCode #213: House Robber II in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.
What Is the House Robber II Problem?
This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.
For this problem, we will use two dynamic programming passes because it gives a clean and optimized solution.
Example input: nums = [4, 1, 2, 9, 5] Expected result: Output: 13 Explanation: Best circular choice is 4 + 9.
Beginner-Friendly Idea
The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.
At each step, ask: “What do I already know, and how does the current value change my answer?”
Using our example: nums = [4, 1, 2, 9, 5] Approach: two dynamic programming passes We update variables step by step until we reach: Output: 13
Why Do We Use This Approach?
A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.
That is why two dynamic programming passes is useful for this problem.
Step-by-Step Explanation
Let us dry run the algorithm using a custom example.
Step 1 Use this custom example. nums = [4, 1, 2, 9, 5] We will solve it using two dynamic programming passes. Step 2 Look at the first important value from the example and create the variables needed by the algorithm. current_state = based on the first value answer = not finished yet Step 3 Move to the next useful value and update the state. The algorithm compares the new value with the old state. If the new value improves the answer, we update the answer. Step 4 Continue this process until all useful values are processed. After processing the example, we get: Output: 13 Why? Best circular choice is 4 + 9.
Important Code Logic
The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.
Think like this: old_state = what we knew before current_value = value we are checking now new_state = updated result after using current_value For our example, the final state gives: Output: 13
Example 1
Input: nums = [4, 1, 2, 9, 5] Output: Output: 13 Explanation: Best circular choice is 4 + 9.
Example 2
Input: nums = [2, 8, 4, 9, 3] Output: 17 Explanation: Best circular choice is 8 + 9.
Python Code
Here is the complete Python solution for LeetCode #213.
class CircularHouseRobber:
def rob(self, nums):
if len(nums) == 1:
return nums[0]
def rob_line(houses):
rob_previous = 0
skip_previous = 0
for money in houses:
new_rob = skip_previous + money
new_skip = max(skip_previous, rob_previous)
rob_previous = new_rob
skip_previous = new_skip
return max(rob_previous, skip_previous)
return max(rob_line(nums[:-1]), rob_line(nums[1:]))
robber = CircularHouseRobber()
print(robber.rob([4, 1, 2, 9, 5])) # Output: 13
print(robber.rob([2, 3, 2])) # Output: 3Java Code
Here is the complete Java solution for LeetCode #213.
class CircularHouseRobber {
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 start, int end) {
int robPrevious = 0;
int skipPrevious = 0;
for (int i = start; i <= end; i++) {
int newRob = skipPrevious + nums[i];
int newSkip = Math.max(skipPrevious, robPrevious);
robPrevious = newRob;
skipPrevious = newSkip;
}
return Math.max(robPrevious, skipPrevious);
}
public static void main(String[] args) {
CircularHouseRobber robber = new CircularHouseRobber();
System.out.println(robber.rob(new int[] {4, 1, 2, 9, 5})); // Output: 13
System.out.println(robber.rob(new int[] {2, 3, 2})); // Output: 3
}
}Time and Space Complexity
Time Complexity: O(n)
The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.
Space Complexity: O(n)
The extra space is used for the variables or data structures needed by the optimized approach.
Final Summary
LeetCode #213: House Robber II becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.