I recognized this pretty quickly as a DP problem but still fumbled the transition for a few minutes.
Use dynamic programming where dp[i][j] represents the number of permutations of length i with exactly j inverse pairs. 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. Return dp[m][n] modulo 10^9+7.
Pro tip: Mention that the recurrence can be optimized using a sliding window (prefix sums) to avoid O(m*n^2) time, and clarify that the answer is 0 if n exceeds the maximum possible inversions m*(m-1)/2.
Let dp[i][j] be the number of permutations of length i with exactly j inverse pairs. 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 inverse pairs. Thus, dp[i][j] = sum_{k=0}^{min(j, i-1)} dp[i-1][j-k].
Compute prefix sums of dp[i-1] to calculate 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. Apply modulo 10^9+7 at each addition 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.