
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 −
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
- Related Articles
- House Robber II in C++
- House Robber III in C++
- Paint House II in C++
- A Tiger in the House
- Program to find minimum total distance between house and nearest mailbox in Python
- Determining full house in poker - JavaScript
- A House Is Not a Home
- House of People: Meaning and Composition
- Describe the ‘Green House Effect’ in your own words.
- Does vastu really effects the people living in the house?
- How to keep lizards away from your house?
- What is the difference between home and house?
- What measures would you take to conserve electricity in your house?
- You want to buy a house. Would you like to buy a house having windows but no ventilators? Explain your answer.
- A dealer sold a house for Rs.150000 by making a profit of Rs. 8000. Find the cost price of the house.

Advertisements