LeetCode 题解工作台
生成数组
给定三个整数 n 、 m 和 k 。考虑使用下图描述的算法找出正整数数组中最大的元素。 请你构建一个具有以下属性的数组 arr : arr 中包含确切的 n 个整数。 1 其中 (0 。 将上面提到的算法应用于 arr 之后, search_cost 的值等于 k 。 返回在满足上述条件的情况下构建…
2
题型
4
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
假设 表示长度为 ,搜索代价为 ,且最大值为 的方案数。考虑第 个数: 若第 个数没有改变搜索代价,说明它不严格大于前 个数,也就是说, 是从 转移而来,即数组的前 个数的最大值已经是 ,并且第 个数没有改变最大值,因此第 个数的可选范围是 ,共有 种可选方案。即
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给定三个整数 n、m 和 k 。考虑使用下图描述的算法找出正整数数组中最大的元素。

请你构建一个具有以下属性的数组 arr :
arr中包含确切的n个整数。1 <= arr[i] <= m其中(0 <= i < n)。- 将上面提到的算法应用于
arr之后,search_cost的值等于k。
返回在满足上述条件的情况下构建数组 arr 的 方法数量 ,由于答案可能会很大,所以 必须 对 10^9 + 7 取余。
示例 1:
输入:n = 2, m = 3, k = 1 输出:6 解释:可能的数组分别为 [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]
示例 2:
输入:n = 5, m = 2, k = 3 输出:0 解释:没有数组可以满足上述条件
示例 3:
输入:n = 9, m = 1, k = 1 输出:1 解释:唯一可能的数组是 [1, 1, 1, 1, 1, 1, 1, 1, 1]
提示:
1 <= n <= 501 <= m <= 1000 <= k <= n
解题思路
方法一:动态规划
假设 表示长度为 ,搜索代价为 ,且最大值为 的方案数。考虑第 个数:
若第 个数没有改变搜索代价,说明它不严格大于前 个数,也就是说, 是从 转移而来,即数组的前 个数的最大值已经是 ,并且第 个数没有改变最大值,因此第 个数的可选范围是 ,共有 种可选方案。即
若第 个数改变了搜索代价,说明数组前 个数的最大值小于 ,并且第 个数恰好为 。此时 是从所有 转移而来,其中 。即
综上,可得
答案为
时间复杂度 。
class Solution:
def numOfArrays(self, n: int, m: int, k: int) -> int:
if k == 0:
return 0
dp = [[[0] * (m + 1) for _ in range(k + 1)] for _ in range(n + 1)]
mod = 10**9 + 7
for i in range(1, m + 1):
dp[1][1][i] = 1
for i in range(2, n + 1):
for c in range(1, min(k + 1, i + 1)):
for j in range(1, m + 1):
dp[i][c][j] = dp[i - 1][c][j] * j
for j0 in range(1, j):
dp[i][c][j] += dp[i - 1][c - 1][j0]
dp[i][c][j] %= mod
ans = 0
for i in range(1, m + 1):
ans += dp[n][k][i]
ans %= mod
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate break down the dynamic programming transition states?
- question_mark
How well does the candidate optimize the solution using prefix sums?
- question_mark
Is the candidate aware of the need to use modulo operations to prevent overflow?
常见陷阱
外企场景- error
Overlooking the constraints and not managing the dynamic programming transitions correctly.
- error
Failing to use prefix sum optimization, leading to excessive computation time.
- error
Not correctly handling the modulo operation, which can lead to overflow or incorrect results.
进阶变体
外企场景- arrow_right_alt
Change the value of k to test the candidate's ability to adapt the DP table to different constraints.
- arrow_right_alt
Vary the range of possible values for m to test how the solution scales.
- arrow_right_alt
Increase the size of the array n and ask for optimizations to handle larger inputs efficiently.