House Robber in Python


Suppose there is a city, and each house in the city has a certain amount. One robber wants to rob the money in one single night. The city has one security system, that is as if two consecutive houses are broken on the same night, then it will automatically call the police. So we have to find how the maximum amount the robber can rob?

One array is provided, at index i, the A[i] is the amount that is present in i-th house. Suppose the array is like: A = [2, 7, 10, 3, 1], then the result will be 13. The maximum is taking from house1 (value 2), from house3 (value 10), and house5 (value 1), so total is 13

To solve this, we will follow this approach −

  • take prev1 := 0 and prev2 = 0
  • for i = 0 to the length of A −
    • temp := prev1
    • prev1 := maximum of prev2 + A[i] and prev1
    • prev2 = temp
  • return prev1

Example

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def rob(self, nums):
      """
      :type nums: List[int]
      :rtype: int
      """
      prev2 = 0
      prev1 = 0
      for i in range(0,len(nums)):
         temp = prev1
         prev1 = max(prev2+nums[i],prev1)
         prev2 = temp
      return prev1
ob1 = Solution()
print(ob1.rob([2,7,10,3,1]))

Input

nums = [2,7,10,3,1]

Output

13

Updated on: 28-Apr-2020

788 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements