This approach involves splitting the problem into two scenarios: robbing from house 0 to house n-2, and from house 1 to house n-1. The aim is to apply the linear version of the House Robber problem to each scenario separately and then take the maximum of the two resulting summed values.
Time Complexity: O(n).
Space Complexity: O(1).
1
2class Solution {
3 private int robLinear(int[] nums, int start, int end) {
4 int prev1 = 0, prev2 = 0;
5 for (int i = start; i < end; i++) {
6 int temp = prev1;
7 prev1 = Math.max(nums[i] + prev2, prev1);
8 prev2 = temp;
9 }
10 return prev1;
11 }
12
13 public int rob(int[] nums) {
14 int n = nums.length;
15 if (n == 1) return nums[0];
16 return Math.max(robLinear(nums, 0, n - 1), robLinear(nums, 1, n));
17 }
18}
19
This Java solution follows a similar approach using a helper method robLinear
to solve the problem twice by excluding first and last house respectively. It returns the maximal result.
This approach implements a memoized version of the dynamic programming solution to avoid recomputing values. We explore two scenarios of the circle, taking into account the cycles explicitly by caching intermediate results.
Time Complexity: O(n).
Space Complexity: O(n) for the memoization array.
1
2#include <string.h>
3
4int memo[101];
5
6int robLinearMemo(int* nums, int start, int end) {
7 memset(memo, -1, sizeof(memo));
8 return robHelper(nums, start, end);
9}
10
11int robHelper(int* nums, int start, int end) {
12 if (start >= end) return 0;
13 if (memo[start] >= 0) return memo[start];
14 memo[start] = (nums[start] + robHelper(nums, start + 2, end) > robHelper(nums, start + 1, end))
15 ? nums[start] + robHelper(nums, start + 2, end) : robHelper(nums, start + 1, end);
16 return memo[start];
17}
18
19int rob(int* nums, int numsSize) {
20 if (numsSize == 1) return nums[0];
21 int case1 = robLinearMemo(nums, 0, numsSize - 1);
22 int case2 = robLinearMemo(nums, 1, numsSize);
23 return (case1 > case2) ? case1 : case2;
24}
25
The C solution sets up a memo
array for memoization to store calculated maximums for each house start index. It runs the helper function robHelper
which recursively looks for the maximum stealing options, caching results for efficiency. It applies this to the scenarios that exclude the first and last house respectively.