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 −
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]