K Inverse Pairs Array LeetCode solution in Python
1class Solution:2# A very good description of the dp solution is at3# https://leetcode.com/problems/k-inverse-pairs-array/solution/4# The code below uses two 1D arrays--dp and tmp--instead if a5# 2D array. tmp replaces dp after each i-iteration.6def kInversePairs(self, n: int, k: int) -> int:7dp, mod = [1] + [0] * k, 100000000789for i in range(n):10tmp, sm = [], 011for j in range(k + 1):12sm += dp[j]13if j - i >= 1:14sm -= dp[j - i - 1]15sm %= mod16tmp.append(sm)17dp = tmp18# print(dp) # <-- uncomment this line to get a sense of dp from the print output19# try n = 6, k = 4; your answer should be 49.20return dp[k]