- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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]))
nums = [2,7,10,3,1]
- House Robber II in C++
- House Robber III in C++
- Paint House II in C++
- Program to find minimum total distance between house and nearest mailbox in Python
- What is the difference between home and house?
- How to keep lizards away from your house?
- Does vastu really effects the people living in the house?
- What are some tips to decorate a wedding house?
- C++ code to get maximum profit by house making
- How to keep house cool during summer without using ACs and coolers?
- What safety measures should be adopted by girls who live alone in an independent house?
- How can a lady prepare the budget for her house in order to save more?
- ChainMap in Python
- Namedtuple in Python