LeetCode213: House Robber II, leetcode=robber
Note: This is an extension of House Robber.
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. this time, all houses at this place are arranged in a circle. that means the first house is the neighbor of the last one. meanwhile, the security system for these houses remain the same as for those in the previous street.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
Credits:
Special thanks to @ Freezen for adding this problem and creating all test cases.
After continuing with the previous House Robber I, I thought about how to solve it for a long time. The conditional DP problem must be converted to the standard DP problem, which becomes the key.
The key here is that the last room N is connected to the first room, which can be converted as follows:
Considering the robbery of 0th rooms, the problem is to ask for the robbery of 0th ~ Maximum number of rooms in N-1.
Considering not to rob 0th rooms, the problem is to ask for a robbery of 1st ~ The maximum number of N rooms.
The two problems after the above conversion are the problems in House Robber I. The maximum value of the above two solutions is the solution of this question.
When doing this, we found that the code in House Robber I can be further optimized. We can also omit the array and only use two variables to store the value, in this way, the space complexity also drops to O (1 ). The code is better.
This is because House Robber I only needs to compare the size of the [I-2] + nums [I] And A [I-1], so the array in House Robber I can also be omitted, instead, you only need two variables to store two values, which saves more space. Here pLast stores the value of A [I-1] in House Robber I, and ppLast stores the value of A [I-2] in House Robber I, with the same logic as House Robber I.
Runtime: 0 ms
Class Solution {public: int rob (vector <int> & nums) {int length = nums. size (); if (length = 0) return 0; if (length = 1) return nums [0]; return max (robDiv (nums, 0, length-2), robDiv (nums, 1, length-1);} int robDiv (vector <int> & nums, int first, int last) {// because you only need to compare the size of the [I-2] + nums [I] And A [I-1], you can also omit the array in House Robber I, // you only need two variables to store two values, which saves more space. // Here pLast stores the value of A [I-1] in House Robber I, // ppLast stores the value of A [I-2] in House Robber I, the logic is the same as that of House Robber I. Int pLast = 0, ppLast = 0; for (int I = first; I <= last; I ++) {int tmp = pLast; pLast = max (ppLast + nums [I], pLast); ppLast = tmp;} return pLast ;}};