Use dynamic programming where dp[i][j] represents the number of permutations of length i with exactly j inversions. The recurrence is dp[i][j] = sum_{k=0}^{min(j, i-1)} dp[i-1][j-k], which can be optimized with prefix sums to O(m*n) time and O(n) space. Return dp[m][n] modulo 10^9+7.
Pro tip: Mention that the maximum number of inversions for length m is m*(m-1)/2, so if n exceeds this, return 0 immediately. Also, use a sliding window to compute the prefix sums efficiently, reducing the time complexity from O(m*n^2) to O(m*n).
Let dp[i][j] be the number of permutations of length i with exactly j inversions. Initialize dp[0][0] = 1 and all other entries to 0.
When inserting the largest element i into a permutation of length i-1, it can create between 0 and i-1 new inversions. So dp[i][j] = sum_{k=0}^{min(j, i-1)} dp[i-1][j-k].
Maintain a running sum of the last i values of dp[i-1] to compute each dp[i][j] in O(1) time, reducing the overall time complexity to O(m*n).
If n > m*(m-1)/2, return 0. Perform all additions modulo 10^9+7 to prevent overflow.
After filling the DP table up to m and n, return dp[m][n] modulo 10^9+7.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.