Advertisement
kosievdmerwe

Untitled

Nov 1st, 2021
71
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 deleteAndEarn(self, nums: List[int]) -> int:
  3.         nums.sort()
  4.        
  5.         # Create an array starting with 0 and ending with 0, so that each run of
  6.         # adjacent numbers are separated by 0s and repeated numbers are summed
  7.         # together
  8.         values = [0]
  9.         cur_num = None
  10.         for n in nums:
  11.             if n != cur_num:
  12.                 values.append(0)
  13.                 if cur_num is not None and cur_num + 1 != n:
  14.                     values.append(0)
  15.                 cur_num = n
  16.             values[-1] += n
  17.         values.append(0)
  18.        
  19.         N = len(values)
  20.        
  21.         # DP[i] = maximum value for values[:i + 1], where if you pick value[j],
  22.         # you're not allowed to pick value[j - 1] or value[j + 1]
  23.         dp = [0] * (N - 1)
  24.         for i in range(1, N - 1):
  25.             dp[i] = max(dp[i - 1], dp[i - 2] + values[i])
  26.        
  27.         return dp[-1]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement