imashutosh51

Maximum sum such that no two elements are adjacent

Nov 3rd, 2022 (edited)
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.54 KB | None | 0 0
  1. At each house, you only have two choices:
  2. Skip it: keep whatever total you had up to the previous house.
  3. Rob it: take this house’s money + the best total up to two houses back (since you can’t use the previous one).
  4.  
  5. You pick whichever is bigger:
  6. best at house i = max(best at i-1,  nums[i] + best at i-2)
  7.  
  8. def rob(nums):
  9.     prev2 = 0   # best up to two houses back
  10.     prev1 = 0   # best up to the previous house
  11.  
  12.     for x in nums:
  13.         current = max(prev1, x + prev2)
  14.         prev2 = prev1
  15.         prev1 = current
  16.  
  17.     return prev1
Advertisement
Add Comment
Please, Sign In to add comment