198. House Robber 213. House Robber II
Solution
If we rob the curr house, we cannot rob curr-1 house.
- Keep
max_2_house_beforeas the amount we can get if we do NOT robcurr-1, i.e. we can robcurr. - Keep
adjacentas the amount we can get if we robcurr-1, i.e. we cannot robcurr. - Althouge we can rob
curr, we do NOT necessarily rob it. We can leave 2 house not robbed to get better result. In this case, we keepadjacentinstead ofmax_2_house_before + curr.
Complexity: O(n)def rob(self, nums): """ :type nums: List[int] :rtype: int """ max_2_house_before, adjacent = 0, 0 for cur in nums: max_2_house_before, adjacent = \ adjacent, max(adjacent, max_2_house_before+cur) return max(max_2_house_before, adjacent)When the houses are in a circle. We can only rob one of the first and the last house. It is the same as rob
nums[1:]andnums[:-1].
PREVIOUSCombination Sum IV
NEXTDecode Ways