[LeetCode] House Robber II
House Robber II
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.
Solution:
This is an upgraded version of theft. Stealing version 1 is a row of houses in a street. Each house has a lot of money. The alarm system is strange. The alarm system generates an alarm only when two adjacent rooms are triggered. Ask how to steal to get the maximum value.
The upgraded version is that this street is no longer lined up, but a circular Street. The first house is adjacent to the last one. Q: How can I obtain the maximum value for stealing?
The initial thought was to record whether the first room was stolen. If it was stolen, the last room could not be stolen. Then we will discuss the situation in detail. But how do I record the first room was stolen? It seems troublesome.
In fact, there can be two-way scanning, the first scan from left to right, using dynamic planning, if d [len-2] = d [len-1], that is, the last room we did not steal, this situation is the same as linear Street, return d [len-1] can, if not equal, indicating linear Street, the last room to steal, however, we do not know whether the first room was stolen. Therefore, we still need to scan the room from left to right. We also use dynamic planning to obtain dr [].
Now there are two dynamic planning arrays d [] and dr [], note d [] d [len-1]! = D [len-2]. We don't know if the first room was stolen. If the first room was stolen and the last room could not be stolen, then we returned d [len-2]. If the first room is not stolen, we will return dr [1], regardless of whether the last room is stolen. Therefore, we only need to return the greater limit of dr [1] and d [len-2.
The code is easy to understand, and the more difficult it is to explain, the better it is ~ Ps, is the leetCode timed out? Why does it take 0 ms for my code to run?
class Solution {public: int rob(vector
& nums) { int len = nums.size(); if(len == 0){ return 0; } if(len == 1){ return nums[0]; } if(len == 2){ return max(nums[0], nums[1]); } int d[len]; d[0]=nums[0]; d[1]=max(nums[0], nums[1]); for(int i=2; i
=0; i--){ dr[i]=max(dr[i+1], nums[i]+dr[i+2]); } return max(dr[1], d[len-2]); }};