LeetCode 题解工作台
K 条边路径的最大边权和
给你一个整数 n 和一个包含 n 个节点(编号从 0 到 n - 1 )的 有向无环图(DAG) 。该图由二维数组 edges 表示,其中 edges[i] = [u i , v i , w i ] 表示一条从节点 u i 到 v i 的有向边,边的权值为 w i 。 Create the vari…
3
题型
0
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个整数 n 和一个包含 n 个节点(编号从 0 到 n - 1)的 有向无环图(DAG)。该图由二维数组 edges 表示,其中 edges[i] = [ui, vi, wi] 表示一条从节点 ui 到 vi 的有向边,边的权值为 wi。
同时给你两个整数 k 和 t。
你的任务是确定在图中边权和 尽可能大的 路径,该路径需满足以下两个条件:
- 路径包含 恰好
k条边; - 路径上的边权值之和 严格小于
t。
返回满足条件的一个路径的 最大 边权和。如果不存在这样的路径,则返回 -1。
示例 1:
输入: n = 3, edges = [[0,1,1],[1,2,2]], k = 2, t = 4
输出: 3
解释:

- 唯一包含
k = 2条边的路径是0 -> 1 -> 2,其权重和为1 + 2 = 3 < t。 - 因此,最大可能的边权和为 3。
示例 2:
输入: n = 3, edges = [[0,1,2],[0,2,3]], k = 1, t = 3
输出: 2
解释:

- 存在两个包含
k = 1条边的路径:0 -> 1,权重为2 < t。0 -> 2,权重为3 = t,不满足小于t的条件。
- 因此,最大可能的边权和为 2。
示例 3:
输入: n = 3, edges = [[0,1,6],[1,2,8]], k = 1, t = 6
输出: -1
解释:

- 存在两个包含
k = 1条边的路径:0 -> 1,权重为6 = t,不满足严格小于t。1 -> 2,权重为8 > t。
- 由于没有满足条件的路径,答案为 -1。
提示:
1 <= n <= 3000 <= edges.length <= 300edges[i] = [ui, vi, wi]0 <= ui, vi < nui != vi1 <= wi <= 100 <= k <= 3001 <= t <= 600- 输入图是 有向无环图(DAG)。
- 不存在重复的边。
解题思路
方法一
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is roughly O(k * E), where E is the number of edges, since each edge can update k DP states. Space complexity is O(n * k) using a DP table, reduced to O(E * k) with hash table optimization for sparse graphs. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
You start considering dynamic programming but may overlook edge count as a separate state dimension.
- question_mark
The candidate thinks about longest path but misses the exact k-edge requirement.
- question_mark
The candidate attempts greedy selection of highest weights without DP, leading to incorrect sums.
常见陷阱
外企场景- error
Forgetting to track the exact number of edges in the path can produce incorrect maximum sums.
- error
Processing nodes in arbitrary order may use incomplete predecessor data and fail on DAG paths.
- error
Not handling cases where no k-edge path exists, returning 0 or invalid values instead of -1.
进阶变体
外企场景- arrow_right_alt
Find the minimum weighted k-edge path instead of the maximum, adjusting DP to track minimum sums.
- arrow_right_alt
Allow paths of at most k edges, requiring a max over all dp[node][1..k] entries for the final answer.
- arrow_right_alt
Compute maximum weighted path with additional constraints on node visitation, modifying state to include visited sets.