Advertisement
smj007

Untitled

Feb 13th, 2024
1,243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.99 KB | None | 0 0
  1. # Iterative DP with mem with n elements in DP variable
  2. class Solution:
  3.     def rob(self, nums: List[int]) -> int:
  4.  
  5.         n = len(nums)
  6.  
  7.         dp = [0]*(n)
  8.         dp[0] = nums[0]
  9.         if len(nums) == 1:
  10.             return dp[0]
  11.         dp[1] = max(dp[0], nums[1])
  12.         if len(nums) == 2:
  13.             return dp[1]
  14.  
  15.         max_so_far = -math.inf
  16.  
  17.         for i in range(2, n):
  18.             dp[i] = max(dp[i-2] + nums[i], dp[i-1])
  19.  
  20.             # if there were negative elements as well
  21.             # dp[i] = max(dp[i-2] + nums[i], dp[i-1], dp[i-2], nums[i])
  22.  
  23.             # relevant when there are negative numbers; but in general a good practice
  24.             max_so_far = max(dp[i], max_so_far)
  25.  
  26.         return max_so_far
  27.  
  28. # Iterative DP with mem with n+2 elements in DP variable    
  29. class Solution:
  30.     def rob(self, nums: List[int]) -> int:
  31.  
  32.         n = len(nums)
  33.  
  34.         dp = [0]*(n+2)
  35.         max_so_far = -math.inf
  36.  
  37.         for i in range(2, n+2):
  38.             dp[i] = max(dp[i-1], dp[i-2] + nums[i-2])
  39.  
  40.             # if there were negative elements as well
  41.             # dp[i] = max(dp[i-2] + nums[i], dp[i-1], dp[i-2], nums[i])
  42.  
  43.             # relevant when there are negative numbers; but in general a good practice
  44.             max_so_far = max(max_so_far, dp[i])
  45.  
  46.         return max_so_far
  47.  
  48. # Iterative without any extra space
  49. class Solution:
  50.     def rob(self, nums: List[int]) -> int:
  51.  
  52.         # prev2 = max_ending_here 2 iterations back
  53.         # prev1 = max_ending_here 1 iteration back
  54.         prev2 = 0
  55.         prev1 = 0
  56.         max_so_far = -math.inf
  57.  
  58.         for n in nums:
  59.             # for the current number
  60.             max_ending_here = max(prev2+n, prev1)
  61.            
  62.             # for the next loop
  63.             prev2 = prev1
  64.             prev1 = max_ending_here
  65.  
  66.             # relevant when there are negative numbers; but in general a good practice
  67.             max_so_far = max(max_so_far, max_ending_here)
  68.  
  69.         return max_so_far
  70.        
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement