Description Link to heading
Solution Link to heading
Referring to 198.house-robber, there be another constraint that first and last can’t be selected at the same time. So we can split the array into two part: one for [0, n - 1)
, another for [1, n)
, corresponding to dp0
and dp1
respectively, just return max(dp0, dp1)
.
Code Link to heading
class Solution {
public:
int rob(vector<int>& nums) {
if (nums.size() == 0) return 0;
if (nums.size() == 1) return nums[0];
int result1 = robRange(nums, 0, nums.size() - 2);
int result2 = robRange(nums, 1, nums.size() - 1);
return max(result1, result2);
}
int robRange(vector<int>& nums, int start, int end) {
if (end == start) return nums[start];
vector<int> dp(nums.size());
dp[start] = nums[start];
dp[start + 1] = max(nums[start], nums[start + 1]);
for (int i = start + 2; i <= end; i++) {
dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]);
}
return dp[end];
}
};