https://leetcode.com/problems/house-robber/
198. House Robber
- Total Accepted: 101581
- Total Submissions: 275668
- Difficulty: Easy
- Contributors: Admin
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
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.
Code (Naive)
class Solution(object): def rob(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 return max(nums[0] + self.helper(nums, 2), self.helper(nums, 1)) def helper(self, nums, idx): if idx >= len(nums): return 0 else: return max(nums[idx] + self.helper(nums, idx+2), self.helper(nums, idx+1))
Idea
This is my naive code. While this seems working, it actually takes O(2^N) time and O(N) space.
Code
class Solution(object): def rob(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 prev, cur = 0, 0 for n in nums: new_cur = max(prev+n, cur) prev = cur cur = new_cur return cur
Idea
It uses two caches: prev
, cur
. For every n
in nums
, prev
is the maximum stolen amount until the element which is two elements apart from n
. cur
is the maximum stolen amount until the element before n
. Therefore, the maximum stolen amount until n
, new_cur
, is max(prev+n, cur)
.
Reference: https://discuss.leetcode.com/topic/17199/python-solution-3-lines