Advertisement
kosievdmerwe

Original Submission

Sep 10th, 2021
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | None | 0 0
  1. class DPState:
  2.     def __init__(self):
  3.         # number which end at this
  4.         self.num_two_length = 0
  5.         self.num_arithmetic = 0
  6.  
  7. class Solution:
  8.     def numberOfArithmeticSlices(self, nums: List[int]) -> int:
  9.         N = len(nums)
  10.         dp = [{} for _ in range(N)]
  11.        
  12.         ans = 0
  13.         for i in range(N):
  14.             for j in range(i + 1, N):
  15.                 delta = nums[j] - nums[i]
  16.                 if delta == 0:  # We handle these below
  17.                     continue
  18.                    
  19.                 if delta not in dp[j]:
  20.                     dp[j][delta] = DPState()
  21.                
  22.                 dp[j][delta].num_two_length += 1
  23.                 if delta not in dp[i]:
  24.                     continue
  25.                    
  26.                 to_add = dp[i][delta].num_two_length + dp[i][delta].num_arithmetic
  27.                 dp[j][delta].num_arithmetic += to_add
  28.                 ans += to_add
  29.                
  30.         # Handle duplicates
  31.         for k, cnt in Counter(nums).items():
  32.             if cnt < 3:
  33.                 continue
  34.            
  35.             ans += (
  36.                 2 ** cnt
  37.                 - 1  # Remove nothing choice
  38.                 - cnt  # Remove single element choice
  39.                 - cnt * (cnt - 1) // 2  # Remove double element choice.
  40.             )
  41.            
  42.         return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement