LeetCode 题解工作台
最高的广告牌
你正在安装一个广告牌,并希望它高度最大。这块广告牌将有两个钢制支架,两边各一个。每个钢支架的高度必须相等。 你有一堆可以焊接在一起的钢筋 rods 。举个例子,如果钢筋的长度为 1 、 2 和 3 ,则可以将它们焊接在一起形成长度为 6 的支架。 返回 广告牌的最大可能安装高度 。如果没法安装广告牌…
2
题型
5
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
我们设计一个函数 $dfs(i, j)$,表示从第 根钢筋开始,且当前高度差为 时,两边的最大共同高度。那么答案就是 $dfs(0, 0)$。 函数 $dfs(i, j)$ 的计算过程如下:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
你正在安装一个广告牌,并希望它高度最大。这块广告牌将有两个钢制支架,两边各一个。每个钢支架的高度必须相等。
你有一堆可以焊接在一起的钢筋 rods。举个例子,如果钢筋的长度为 1、2 和 3,则可以将它们焊接在一起形成长度为 6 的支架。
返回 广告牌的最大可能安装高度 。如果没法安装广告牌,请返回 0 。
示例 1:
输入:[1,2,3,6]
输出:6
解释:我们有两个不相交的子集 {1,2,3} 和 {6},它们具有相同的和 sum = 6。
示例 2:
输入:[1,2,3,4,5,6]
输出:10
解释:我们有两个不相交的子集 {2,3,5} 和 {4,6},它们具有相同的和 sum = 10。
示例 3:
输入:[1,2] 输出:0 解释:没法安装广告牌,所以返回 0。
提示:
0 <= rods.length <= 201 <= rods[i] <= 1000sum(rods[i]) <= 5000
解题思路
方法一:记忆化搜索
我们设计一个函数 ,表示从第 根钢筋开始,且当前高度差为 时,两边的最大共同高度。那么答案就是 。
函数 的计算过程如下:
如果 ,此时判断 是否为 ,如果是则返回 ,否则返回 。
如果 ,此时有三种情况:
- 不选择第 根钢筋,此时 ;
- 选择第 根钢筋,并且放置在原本高度较高的一边,那么 ;
- 选择第 根钢筋,并且放置在高度较低的一边,此时共同高度增加了 ,那么 。
我们取这三种情况下的最大值,即可得到 的值。
为了避免重复计算,我们使用一个二维数组 来记录已经计算过的 的值,调用 时,如果 已经被计算过,则直接返回 。否则,我们计算 的值,并将其存入 。
时间复杂度 ,空间复杂度 。其中 和 分别为 的长度和 中所有元素的和。
class Solution:
def tallestBillboard(self, rods: List[int]) -> int:
@cache
def dfs(i: int, j: int) -> int:
if i >= len(rods):
return 0 if j == 0 else -inf
ans = max(dfs(i + 1, j), dfs(i + 1, j + rods[i]))
ans = max(ans, dfs(i + 1, abs(rods[i] - j)) + min(j, rods[i]))
return ans
return dfs(0, 0)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n\cdot m) |
| 空间 | O(m) |
面试官常问的追问
外企场景- question_mark
Candidate should demonstrate an understanding of dynamic programming and subset sum problems.
- question_mark
Look for clarity in explaining the state transition logic and how the DP table is updated.
- question_mark
The candidate should optimize the solution in terms of both time and space complexity.
常见陷阱
外企场景- error
Misunderstanding the requirement of two disjoint subsets; candidate might focus only on a single subset sum.
- error
Failing to properly optimize space complexity, resulting in an inefficient solution.
- error
Not correctly updating the DP table or missing necessary states, which could lead to an incorrect answer.
进阶变体
外企场景- arrow_right_alt
Consider a variation where rod lengths are constrained to a specific range.
- arrow_right_alt
Extend the problem to handle more complex rod configurations or additional constraints.
- arrow_right_alt
Modify the problem to work in a scenario where rod lengths must follow a specific pattern or sequence.