Advertisement
DeepRest

K Inverse Pairs Array

Jul 17th, 2022 (edited)
1,349
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. #Bottom up DP
  2. '''
  3. Intuition:
  4. Consider a sorted array of length n. Now fix the position of the smallest element, by iterating from 1 to n keeping the remaining array intact.
  5. For eg. For n = 3, take [1, 2, 3], fix positions of 1 so: [1, 2, 3], [2, 1, 3] and [2, 3, 1]
  6. For each of these permutations there are already some reverse pairs equal to index of smallest element like for:
  7. [1, 2, 3] => 0 reverse pairs
  8. [2, 1, 3] => 1 reverse pairs
  9. [2, 3, 1] => 2 reverse pairs
  10. So inorder to make k reverse pairs for each of them we need to now find the arrangement of remaining n-1 elements with k-i reverse pairs (i being the no. of reverse pairs already in permutation). Now no matter how we arrange these n-1 elements the reverse pairs they are going to form with the smallest element (the excluded one) will remain i.
  11. '''
  12.  
  13. class Solution:
  14.     def kInversePairs(self, n: int, k: int) -> int:
  15.         MOD = int(1e9+7)
  16.        
  17. #Memoization
  18.         """
  19.        @lru_cache(None)
  20.        def solve(n, k):
  21.            if k == 0:
  22.                return 1
  23.            
  24.            if n == 1:
  25.                return 0
  26.            
  27.            ans = 0
  28.            for i in range(min(n, k+1)):
  29.                ans += solve(n-1, k-i)%MOD
  30.                
  31.            return ans%MOD
  32.        
  33.        return solve(n, k)
  34.        """
  35.        
  36.         dp = [0]*(k+1) #for n = 1
  37.         dp[0] = 1 #for k = 1
  38.         for i in range(2, n+1):
  39.             tmp = [0]*(k+1)
  40.             slidingSum = 0
  41.             for j in range(k+1):
  42.                 slidingSum += dp[j]%MOD
  43.                 if j >= i:
  44.                     slidingSum -= dp[j-i]%MOD
  45.                 tmp[j] = slidingSum%MOD
  46.             dp = tmp[:]
  47.         return dp[-1]%MOD
  48.            
  49.        
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement