Dynamic programming · Medium
House Robber II: the idea to remember.
Choose nonadjacent houses on a circle, maximizing their nonnegative total value.
The core insight
Solve two linear ranges: exclude the last house, or exclude the first house.
Why it works
The first and last houses cannot both be chosen. Every valid solution belongs to at least one of those two ranges.
The mistake to avoid
Handle a one house circle separately; otherwise both excluded ranges would be empty.
Time: O(n)Space: O(1)
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
int rob(int[] nums) {
if (nums.length == 1) return nums[0];
return Math.max(linear(nums, 0, nums.length - 1), linear(nums, 1, nums.length));
}
int linear(int[] nums, int start, int end) {
int two = 0, one = 0;
for (int i = start; i < end; i++) {
int next = Math.max(one, two + nums[i]);
two = one; one = next;
}
return one;
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.