Advertisement
bobbye

Untitled

Apr 10th, 2024
638
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.93 KB | None | 0 0
  1. class Solution:
  2.     def rob(self, nums: List[int]) -> int:
  3.         # Return the maximum of three scenarios:
  4.         # 1. Robbing the first house and skipping the last house.
  5.         # 2. Robbing the last house and skipping the first house.
  6.         return max(nums[0], self.helper(nums[1:]), self.helper(nums[:-1]))
  7.  
  8.     # Helper function to calculate the maximum amount of money
  9.     # that can be robbed using dynamic programming.
  10.     def helper(self, nums):
  11.         rob1, rob2 = 0, 0  
  12.        
  13.         # Iterate through the house values
  14.         for n in nums:
  15.             # Calculate the new maximum amount considering two scenarios:
  16.             # 1. Robbing the current house and the amount obtained from robbing two houses ago.
  17.             # 2. Not robbing the current house and maintaining the previous maximum.
  18.             newRob = max(rob1 + n, rob2)
  19.             rob1 = rob2  
  20.             rob2 = newRob  
  21.         return rob2  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement