<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 {
public:
    int mod = 1e9 + 7;
    int dp[1001][1001];
    int solve(int n, int k)
    {
        if (n == 0) return 0;
        if (k == 0) return 1;
        
        if (dp[n][k] != -1) return dp[n][k];

        int ans = 0;
        // for an array of length n, you can have at max (n-1) inversions
        for (int i = 0; i<= min(k, n-1); i++)
        {
            // why k-i? 
            // I already have i inversions we need k-i inversions from n-1;
            ans = (ans%mod + solve(n-1, k-i)%mod)%mod;
        }

        return dp[n][k] = ans;
    }

    // f(n,k)=f(n−1,k)+f(n−1,k−1)+f(n−1,k−2)+⋯+f(n−1,k−n+1)

    // O(k^n) : w/o memo
    // O(n*k*n) : w/ memo have inner loop

    int kInversePairs(int n, int k) {
        // memset(dp, -1, sizeof(dp));
        // return solve(n, k); // Memo is failling with TLE
        int t[1001][1001] = {0};
        // t[i][j] => total no of arrays (1 to i) of size i & exactly j inversions

        for (int i=0; i<= n; i++)
        {
            t[i][0] = 1;
        }

        // for (int i=1; i<=n; i++)
        // {
        //     for(int j=1; j<=k; j++)
        //     {
        //         int res = 0;
        //         // see loop at line 14
        //         for (int inv = 0; inv <= min(j, i-1); inv++)
        //         {
        //             t[i][j] = (t[i][j]%mod + t[i-1][j-inv]%mod)%mod;
        //         }
        //     }
        // }

        // observation
        for (int i=1; i<=n; i++)
        {
            long long cumsum = 1;
            for (int j=1; j<=k; j++)
            {
                cumsum += t[i-1][j];
                if (j >= i)
                {
                    cumsum -= t[i-1][j-i];
                }
                t[i][j] = cumsum % mod;
            }
        }

        return t[n][k];
    }
}; 
16300