Build Array Where You Can Find The Maximum Exactly K Comparisons Problem
Description
LeetCode Problem 1420.
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:
arrhas exactlynintegers.1 <= arr[i] <= mwhere(0 <= i < n).- After applying the mentioned algorithm to
arr, the valuesearch_costis equal tok.
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 10^9 + 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 <= 501 <= m <= 1000 <= k <= n
Solution
Approach: Dynamic Programming on Cost and Maximum
The algorithm's search_cost is the number of times the running maximum changes, where the first element always counts. So we need arrays of length n with values in [1, m] whose prefix maximum increases exactly k times. For k = 0 there are none, so return 0.
Build the arrays one element at a time and let dp[c][j] be the number of arrays of the current length with cost c and maximum j. For length 1, dp[1][j] = 1 for every j. Appending one more element to get next[c][j] can happen in two ways:
- The new element is at most
j, so the maximum and the cost stay the same:dp[c][j] · jways (any of the values1..j). - The new element is
jitself and beats a smaller old maximumj0 < j, which costs one more: the sum ofdp[c − 1][j0]overj0 < j.
Summing over j0 directly would cost an extra factor of m. Instead, walk j upward and keep a running sum of dp[c − 1][1..j−1]. After n − 1 steps, the answer is the sum of dp[k][j] over all j, modulo 10^9 + 7. The product dp[c][j] · j can reach about 10^11, so it needs 64-bit integers (JavaScript numbers are exact up to 253, which is enough).
Complexity: O(n · k · m) time and O(k · m) space.
class Solution:
def numOfArrays(self, n: int, m: int, k: int) -> int:
if k == 0:
return 0 # the first element always counts as one comparison
mod = 10**9 + 7
# dp[c][j] = arrays of the current length with cost c and maximum j
dp = [[0] * (m + 1) for _ in range(k + 1)]
for j in range(1, m + 1):
dp[1][j] = 1
for _ in range(n - 1):
new = [[0] * (m + 1) for _ in range(k + 1)]
for c in range(1, k + 1):
smaller = 0 # sum of dp[c - 1][1..j-1]
for j in range(1, m + 1):
# append a value <= j (max unchanged), or append j as a new maximum
new[c][j] = (dp[c][j] * j + smaller) % mod
smaller = (smaller + dp[c - 1][j]) % mod
dp = new
return sum(dp[k]) % mod