213. House Robber II
Asked at 16Microsoft44Amazon42Bloomberg42Google37Meta33Infosys45Databricks77MakeMyTrip65Docusign64Datadog62Nutanix60ServiceNow55TikTok41DE Shaw38Salesforce28LinkedIn27
Problem
Same as House Robber, but the houses stand in a circle, so the first and last houses are adjacent too.
Example: [2,3,2] → 3; [1,2,3,1] → 4
Circle → the first and last houses can't both be robbed. Answer = max(rob(nums[1:]), rob(nums[:-1])) (single house: itself).
Complexity: O(n) time, O(1) space.
class Solution:
def rob(self, nums: List[int]) -> int:
def line(arr):
prev = cur = 0
for x in arr:
prev, cur = cur, max(cur, prev + x)
return cur
if len(nums) == 1:
return nums[0]
return max(line(nums[1:]), line(nums[:-1]))
assert Solution().rob([2, 3, 2]) == 3
assert Solution().rob([1, 2, 3, 1]) == 4
assert Solution().rob([1]) == 1
class Solution {
public int rob(int[] nums) {
int n = nums.length;
if (n == 1) return nums[0];
return Math.max(line(nums, 0, n - 2), line(nums, 1, n - 1));
}
private int line(int[] a, int lo, int hi) {
int prev = 0, cur = 0;
for (int i = lo; i <= hi; i++) { int nxt = Math.max(cur, prev + a[i]); prev = cur; cur = nxt; }
return cur;
}
}
func rob(nums []int) int {
if len(nums) == 1 {
return nums[0]
}
line := func(arr []int) int {
prev, cur := 0, 0
for _, x := range arr {
prev, cur = cur, max(cur, prev+x)
}
return cur
}
return max(line(nums[1:]), line(nums[:len(nums)-1])) // skip the first or the last house
}