LeetCode 1420: Build Array Where You Can Find The Maximum Exactly K Comparisons

Problem Description

Explanation:

To solve this problem, we can use dynamic programming. We can define a 3D dp array where dp[i][j][k] represents the number of ways to build an array of length i, with maximum element j, and search cost k.

We can iterate over the array length, maximum element, and search cost to fill up the dp array using the following recurrence relation: dp[i][j][k] = dp[i-1][j][k] * j + dp[i-1][j-1][k-1] + dp[i][j-1][k]

Finally, the answer will be the sum of dp[n][j][k] for all possible maximum elements 'j'.

The time complexity of this approach is O(n * m * k) and the space complexity is O(n * m * k).

:

Solutions

class Solution {
    public int numOfArrays(int n, int m, int k) {
        int MOD = 1000000007;
        long[][][] dp = new long[n+1][m+1][k+1];
        
        for (int j = 1; j <= m; j++) {
            dp[1][j][1] = 1;
        }
        
        for (int i = 2; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                for (int cost = 1; cost <= k; cost++) {
                    dp[i][j][cost] = (dp[i][j][cost] + dp[i-1][j][cost] * j) % MOD;
                    for (int prev = 1; prev < j; prev++) {
                        dp[i][j][cost] = (dp[i][j][cost] + dp[i-1][prev][cost-1]) % MOD;
                    }
                    dp[i][j][cost] = (dp[i][j][cost] + dp[i][j-1][cost]) % MOD;
                }
            }
        }
        
        long total = 0;
        for (int j = 1; j <= m; j++) {
            total = (total + dp[n][j][k]) % MOD;
        }
        
        return (int) total;
    }
}

Loading editor...