Build Array Where You Can Find The Maximum Exactly K Comparisons

Similar Problems:

- CheatSheet: LeetCode For Code Interview
- CheatSheet: Common Code Problems & Follow-ups
- Tag: #dynamicprogramming, #intervaldp

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 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 satisify 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]

Example 4:

Input: n = 50, m = 100, k = 25 Output: 34549172 Explanation: Don't forget to compute the answer modulo 1000000007

Example 5:

Input: n = 37, m = 17, k = 7 Output: 418930126

Constraints:

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

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.

- Solution:

## https://code.dennyzhang.com/build-array-where-you-can-find-the-maximum-exactly-k-comparisons ## Basic Ideas: dynamic programming ## ## dp(i, j, k): returns the number of ways with length i, maximum j, cost k ## Final result: dp(n, x, k) x:[1,2,...,m] ## ## Check The last element ## Is the largest ## dp(i-1, x, k-1) ## x: [1, j-1] ## Not the largest ## Previous max is j, so any element no more than j would fit ## dp(i-1, j, k)*j ## ## Complexity: Time O(n*m*k*m), Space O(n*m*k) class Solution(object): def numOfArrays(self, n, m, k): """ :type n: int :type m: int :type k: int :rtype: int """ mod = 10**9+7 dp = [[[0 for _ in range(k+1)] for _ in range(m+1)] for _ in range(n+1)] for j in range(m+1): # only one element and only change dp[1][j][1] = 1 for i in range(1, n+1): for j in range(1, m+1): for p in range(1, k+1): # The last element is not the largest one dp[i][j][p] += dp[i-1][j][p]*j # The last element is the largest one for x in range(1, j): dp[i][j][p] += dp[i-1][x][p-1] return sum([dp[n][j][k] for j in range(1, m+1)])%mod