C++ DP and sliding window beat 92%


  • 0
    B

    when we calculate dp[n][k] we need sum from last one, use sliding window to save time

    int kInversePairs(int n, int k) {
        int permutation = n*(n - 1) / 2;
        if (k > permutation)return 0;
        if (n == 1 || k == 0)return 1;
        k = min(k, permutation - k);
        vector<vector<int>> dp(n, vector<int>(k+1, 0));
        dp[0][0] = 1;
        for (int i = 1; i < n; i++)
        {
            int p = i*(i + 1) / 2+1;
            long sum = 0;
            for (int j = 0; j < min(p, k+1); j++)
            {
                sum += dp[i - 1][j];
                if (j > i)sum -= dp[i - 1][j - i-1];
                dp[i][j] = sum%1000000007;
            }
        }
        return dp[n - 1][k];
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.