[LeetCode] House Robber II

213. House Robber II

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int rob(vector<int>& nums) {
int odd = nums[0], even = 0, afterOdd = 0, afterEven = 0;
for(int i = 1; i < nums.size() - 1; i++) {
if(i & 1) {
odd = max(odd + nums[i], even);
afterOdd = max(afterOdd + nums[i], afterEven);
}
else {
even = max(even, odd + nums[i]);
afterEven = max(afterEven + nums[i], afterOdd);
}
}
if((nums.size() - 1) & 1) {
afterOdd = max(afterOdd + nums.back(), afterEven);
} else {
afterEven = max(afterEven + nums.back(), afterOdd);
}
return max({odd, even, afterOdd, afterEven});
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
int dp[2][101][2];
int dfs(vector<int>& st, int pos, vector<int>& n, int last) {
if(pos == n.size() || (last == 1 and pos == n.size() - 1)) return 0;
if(dp[st[pos]][pos][last] != -1) return dp[st[pos]][pos][last];

if(!st[pos]) {
int r = (pos + 1) % n.size();
if(r) st[r] = 1;
dp[0][pos][last] = dfs(st, pos + 1, n, last) + n[pos];
if(r) st[r] = 0;
dp[0][pos][last] = max(dp[0][pos][last], dfs(st, pos + 1, n, last));
} else {
dp[1][pos][last] = dfs(st, pos + 1, n, last);
}

return dp[st[pos]][pos][last];
}
public:
int rob(vector<int>& nums) {
if(nums.size() == 1) return nums[0];
memset(dp,-1,sizeof(dp));
vector<int> st(nums.size(), 0);
dfs(st, 0, nums,1);
st[0] = 1;
dfs(st, 0, nums,0);

return max(dp[0][0][1], dp[1][0][0]);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/30/PS/LeetCode/house-robber-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.