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 1
Thinking
The search cost is how many times the prefix maximum is updated. \(n\le 50\), \(m\le 100\), so we DP on length, cost, and current maximum.
If position \(i\) does not raise the maximum, it has \(j\) choices and stays at the same cost. If it writes a new maximum \(j\), we sum states whose previous maximum is smaller and whose cost is one less.
\(k=0\) is impossible. Sum \(dp[n][k][\cdot]\) for the answer.
The first DP computes each state by scanning every smaller previous maximum, which adds an \(O(m)\) loop. For a fixed length and search cost, adjacent maxima need almost the same sum: the sum for maximum \(j\) adds only the state at \(j-1\) to the sum for \(j-1\). We can maintain that prefix while increasing \(j\), so each state takes \(O(1)\) time. Only the previous length is needed, so two DP layers suffice.
Let \(dp[c][j]\) count arrays of the current length with search cost \(c\) and maximum \(j\). When we append a value, it either does not raise the maximum (with \(j\) choices) or raises a smaller maximum to \(j\). For each new length, maintain \(\textit{prefix} = \sum_{x=1}^{j-1} dp_{\textit{prev}}[c-1][x]\) while increasing \(j\). Then
Initialize \(dp[1][j]=1\) for arrays of length \(1\). The answer is the sum of \(dp[k][j]\) for \(1 \le j \le m\). The time complexity is \(O(nkm)\), reduced from \(O(nkm^2)\) in Solution 1. Keeping only the previous and next lengths uses \(O(km)\) space instead of \(O(nkm)\).