leetcode-1420-Build Array Where You Can Find The Maximum Exactly K Comparisons
问题
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 exactlyn
integers.1 <= arr[i] <= m
where(0 <= i < n)
.- After applying the mentioned algorithm to
arr
, the valuesearch_cost
is 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:
1 | Input: n = 2, m = 3, k = 1 |
Example 2:
1 | Input: n = 5, m = 2, k = 3 |
Example 3:
1 | Input: n = 9, m = 1, k = 1 |
Example 4:
1 | Input: n = 50, m = 100, k = 25 |
Example 5:
1 | Input: n = 37, m = 17, k = 7 |
Constraints:
1 <= n <= 50
1 <= m <= 100
0 <= k <= n
分析
dp[i][j][k]
表示数组长度为 $i$ ,其中最大的元素是 $j$ ,并且经过 $k$ 的 search_cost。
我们以数组长度 $i$ 为dp的阶段,那么 dp[i][j][k]
可以划分为两类子问题。
dp[i][j][k] = j* dp[i-1][j][k]
,如果现在有一个长度为 i-1 的数组,其最大的元素是 j ,并且经过 search_cost = k 找到它。那么我们经过这个数组得到一个长度为 i 的数组就可以在其最后一位添加1-j
中任意一位数组。(第一个最大元素j不是在数组的最后一位找到的)dp[i][j][k] = SUM (from x = 1 to x = j-1) dp[i-1][x][k-1]
(第一个最大元素j是在数组的最后一位找到的)
则目标就是 SUM from j = 1 to j = m dp[n][j][k]
代码
1 | class Solution { |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/04/22/leetcode-1420/
License: 知识共享署名-非商业性使用 4.0 国际许可协议