<p>For an integer array <code>nums</code>, an <strong>inverse pair</strong> is a pair of integers <code>[i, j]</code> where <code>0 &lt;= i &lt; j &lt; nums.length</code> and <code>nums[i] &gt; nums[j]</code>.</p>

<p>Given two integers n and k, return the number of different arrays consisting of numbers from <code>1</code> to <code>n</code> such that there are exactly <code>k</code> <strong>inverse pairs</strong>. Since the answer can be huge, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> n = 3, k = 0
<strong>Output:</strong> 1
<strong>Explanation:</strong> Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 3, k = 1
<strong>Output:</strong> 2
<strong>Explanation:</strong> The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 1000</code></li>
	<li><code>0 &lt;= k &lt;= 1000</code></li>
</ul>

class Solution:
    def kInversePairs(self, n: int, k: int) -> int:
        MOD = 10**9 + 7
        # dp[n][k] returns number of ways to get k inverse pairs for [1, n]
        dp = [[0]*(k+1) for _ in range(n+1)]
        prefix = [[0] for _ in range(n+1)]

        # prefix[i][j] stores dp[i][0] + dp[i][1] + ... + dp[i][j-1]
        prefix[1].append(1)

        for m in range(1,n+1):
            # One way to arrange [1, m] with 0 inverse pairs, namely the sorted order (increasing)
            dp[m][0] = 1

        for i in range(2, n+1):
            idx = min(k, m*(m-1)//2)
            prefix[i].append(1)
            for j in range(1, 1+idx):
                # there are i positions to insert the value i into some permutation of [1, i-1]
                # Inserting i at index 0 produces i-1 inverse pairs, then i-2 pairs... then so on.
                # Inserting it at the end produces 0 inverse pairs

                # Then, we want to sum:
                #   dp[i][j] = dp[i-1][j] + dp[i-1][j-1] + ... + dp[i-1][j-i+1]
                #            = prefix[i-1][j+1] - prefix[j-i+1]
                r = j+1
                if r >= len(prefix[i-1]):
                    r = len(prefix[i-1])-1

                l = j-i+1
                if l < 0:
                    l = 0
                if l >= len(prefix[i-1]):
                    l = len(prefix[i-1])-1

                dp[i][j] = (prefix[i-1][r] - prefix[i-1][l]) % MOD

                prefix[i].append((dp[i][j] + prefix[i][-1]) % MOD)

        # for i in range(1, n+1):
        #     for j in range(0, k+1):
        #         print(f"i={i} j={j} dp[i][j]={dp[i][j]}")
        #     print("prefix", prefix[i])
        #     print()

        return dp[n][k]
94800