#213
Medium Algorithms House robber ii
Array Dynamic Programming
44.6% acceptance
Jan 12, 2026
11001
189
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Solution
Rust
Time O(2^n)
Space O(n)
impl Solution {
pub fn rob(nums: Vec<i32>) -> i32 {
if nums.len() == 1 { return nums[0]; }
Self::rob_range(&nums, 0, nums.len() - 1).max(Self::rob_range(&nums, 1, nums.len()))
}
fn rob_range(nums: &[i32], start: usize, end: usize) -> i32 {
let mut prev = 0;
let mut curr = 0;
for i in start..end {
let temp = curr;
curr = curr.max(prev + nums[i]);
prev = temp;
}
curr
}
}