Skip to content

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

Description

You are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers:

You should build the array arr which has the following properties:

  • arr has exactly n integers.
  • 1 <= arr[i] <= m where (0 <= i < n).
  • After applying the mentioned algorithm to arr, the value search_cost is equal to k.

Return the number of ways to build the array arr under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 109 + 7.

 

Example 1:

Input: n = 2, m = 3, k = 1
Output: 6
Explanation: The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]

Example 2:

Input: n = 5, m = 2, k = 3
Output: 0
Explanation: There are no possible arrays that satisfy the mentioned conditions.

Example 3:

Input: n = 9, m = 1, k = 1
Output: 1
Explanation: The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]

 

Constraints:

  • 1 <= n <= 50
  • 1 <= m <= 100
  • 0 <= k <= n

 

Solutions

Solution: Dynamic Programming

  • Time complexity: O(nm2k)
  • Space complexity: O(nmk)

 

JavaScript

js
/**
 * @param {number} n
 * @param {number} m
 * @param {number} k
 * @return {number}
 */
const numOfArrays = function (n, m, k) {
  if (k === 0) return 0;
  const MODULO = 10 ** 9 + 7;
  const dp = Array.from({ length: n }, () => {
    return new Array(m + 1)
      .fill('')
      .map(_ => new Array(k + 1).fill(-1));
  });

  const findArrays = (index, maximum, searchCost) => {
    if (index >= n) return searchCost === k ? 1 : 0;
    if (n - index + 1 + searchCost < k) return 0;
    if (dp[index][maximum][searchCost] !== -1) return dp[index][maximum][searchCost];
    const maxNum = searchCost === k ? maximum : m;
    const minCount = findArrays(index + 1, maximum, searchCost) * maximum;
    let result = minCount % MODULO;

    for (let num = maximum + 1; num <= maxNum; num++) {
      const count = findArrays(index + 1, num, searchCost + 1);

      result = (result + count) % MODULO;
    }

    dp[index][maximum][searchCost] = result;

    return result;
  };

  return findArrays(0, 0, 0);
};

Released under the MIT license