Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
You are given an integer n and a Directed Acyclic Graph (DAG) with n nodes labeled from 0 to n - 1. This is represented by a 2D array edges, where edges[i] = [ui, vi, wi] indicates a directed edge from node ui to vi with weight wi.
You are also given two integers, k and t.
Your task is to determine the maximum possible sum of edge weights for any path in the graph such that:
k edges.t.Return the maximum possible sum of weights for such a path. If no such path exists, return -1.
Example 1:
Input: n = 3, edges = [[0,1,1],[1,2,2]], k = 2, t = 4
Output: 3
Explanation:
k = 2 edges is 0 -> 1 -> 2 with weight 1 + 2 = 3 < t.t is 3.Example 2:
Input: n = 3, edges = [[0,1,2],[0,2,3]], k = 1, t = 3
Output: 2
Explanation:
k = 1 edge:
0 -> 1 with weight 2 < t.0 -> 2 with weight 3 = t, which is not strictly less than t.t is 2.Example 3:
Input: n = 3, edges = [[0,1,6],[1,2,8]], k = 1, t = 6
Output: -1
Explanation:
0 -> 1 with weight 6 = t, which is not strictly less than t.1 -> 2 with weight 8 > t, which is not strictly less than t.t, the answer is -1.Constraints:
1 <= n <= 3000 <= edges.length <= 300edges[i] = [ui, vi, wi]0 <= ui, vi < nui != vi1 <= wi <= 100 <= k <= 3001 <= t <= 600Problem summary: You are given an integer n and a Directed Acyclic Graph (DAG) with n nodes labeled from 0 to n - 1. This is represented by a 2D array edges, where edges[i] = [ui, vi, wi] indicates a directed edge from node ui to vi with weight wi. You are also given two integers, k and t. Your task is to determine the maximum possible sum of edge weights for any path in the graph such that: The path contains exactly k edges. The total sum of edge weights in the path is strictly less than t. Return the maximum possible sum of weights for such a path. If no such path exists, return -1.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Dynamic Programming
3 [[0,1,1],[1,2,2]] 2 4
3 [[0,1,2],[0,2,3]] 1 3
3 [[0,1,6],[1,2,8]] 1 6
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3543: Maximum Weighted K-Edge Path
class Solution {
public int maxWeight(int n, int[][] edges, int k, int t) {
List<Pair<Integer, Integer>>[] graph = new List[n];
// dp[i][j] := the set of possible path sums ending at node i with j edges
Map<Integer, Set<Integer>>[] dp = new Map[n];
for (int u = 0; u < n; ++u) {
graph[u] = new ArrayList<>();
dp[u] = new HashMap<>();
}
for (int[] edge : edges) {
final int u = edge[0];
final int v = edge[1];
final int w = edge[2];
graph[u].add(new Pair<>(v, w));
}
for (int u = 0; u < n; ++u) {
dp[u].putIfAbsent(0, new HashSet<>());
dp[u].get(0).add(0); // zero edges = sum 0
}
for (int i = 0; i < k; ++i)
for (int u = 0; u < n; ++u)
if (dp[u].containsKey(i))
for (final int currSum : dp[u].get(i))
for (Pair<Integer, Integer> pair : graph[u]) {
final int v = pair.getKey();
final int w = pair.getValue();
final int newSum = currSum + w;
if (newSum < t) {
dp[v].putIfAbsent(i + 1, new HashSet<>());
dp[v].get(i + 1).add(newSum);
}
}
int ans = -1;
for (int u = 0; u < n; ++u)
if (dp[u].containsKey(k))
for (final int sum : dp[u].get(k))
ans = Math.max(ans, sum);
return ans;
}
}
// Accepted solution for LeetCode #3543: Maximum Weighted K-Edge Path
package main
import "math/big"
// https://space.bilibili.com/206214
func maxWeight1(n int, edges [][]int, k int, t int) int {
if n <= k {
return -1
}
type edge struct{ to, wt int }
g := make([][]edge, n)
for _, e := range edges {
x, y, wt := e[0], e[1], e[2]
g[x] = append(g[x], edge{y, wt})
}
ans := -1
type tuple struct{ x, i, s int }
vis := map[tuple]bool{}
var dfs func(int, int, int)
dfs = func(x, i, s int) {
if i == k {
ans = max(ans, s)
return
}
args := tuple{x, i, s}
if vis[args] {
return
}
vis[args] = true
for _, e := range g[x] {
if s+e.wt < t {
dfs(e.to, i+1, s+e.wt)
}
}
}
for x := range n {
dfs(x, 0, 0)
}
return ans
}
func maxWeight2(n int, edges [][]int, k int, t int) int {
if n <= k {
return -1
}
type edge struct{ to, wt int }
g := make([][]edge, n)
deg := make([]int, n)
for _, e := range edges {
x, y, wt := e[0], e[1], e[2]
g[x] = append(g[x], edge{y, wt})
}
ans := -1
f := make([][]map[int]struct{}, n)
for i := range f {
f[i] = make([]map[int]struct{}, k+1)
for j := range f[i] {
f[i][j] = map[int]struct{}{}
}
}
q := []int{}
for i, d := range deg {
if d == 0 {
q = append(q, i)
}
}
for len(q) > 0 {
x := q[0]
q = q[1:]
f[x][0][0] = struct{}{} // x 单独一个点,路径边权和为 0
for s := range f[x][k] { // 恰好 k 条边
ans = max(ans, s)
}
for _, e := range g[x] {
y, wt := e.to, e.wt
for i, st := range f[x][:k] {
for s := range st {
if s+wt < t {
f[y][i+1][s+wt] = struct{}{}
}
}
}
deg[y]--
if deg[y] == 0 {
q = append(q, y)
}
}
}
return ans
}
func maxWeight3(n int, edges [][]int, k int, t int) int {
if n <= k {
return -1
}
f := make([][]map[int]struct{}, k+1)
for i := range f {
f[i] = make([]map[int]struct{}, n)
for j := range f[i] {
f[i][j] = map[int]struct{}{}
}
}
for i := range f[0] {
f[0][i][0] = struct{}{}
}
for i, sets := range f[:k] {
for _, e := range edges {
x, y, wt := e[0], e[1], e[2]
for s := range sets[x] {
if s+wt < t {
f[i+1][y][s+wt] = struct{}{}
}
}
}
}
ans := -1
for _, set := range f[k] {
for s := range set {
ans = max(ans, s)
}
}
return ans
}
func maxWeight(n int, edges [][]int, k int, t int) int {
if n <= k {
return -1
}
f := make([][]*big.Int, k+1)
for i := range f {
f[i] = make([]*big.Int, n)
for j := range f[i] {
f[i][j] = big.NewInt(0)
}
}
for i := range f[0] {
f[0][i] = big.NewInt(1)
}
p := new(big.Int)
mask := new(big.Int).Sub(p.Lsh(big.NewInt(1), uint(t)), big.NewInt(1))
for i, fi := range f[:k] {
for _, e := range edges {
x, y, wt := e[0], e[1], e[2]
if fi[x].Sign() != 0 {
shifted := p.And(p.Lsh(fi[x], uint(wt)), mask)
f[i+1][y].Or(f[i+1][y], shifted)
}
}
}
ans := 0
for _, bi := range f[k] {
ans = max(ans, bi.BitLen())
}
return ans - 1
}
# Accepted solution for LeetCode #3543: Maximum Weighted K-Edge Path
class Solution:
def maxWeight(self, n: int, edges: list[list[int]], k: int, t: int) -> int:
graph = [[] for _ in range(n)]
# dp[u][i] := the set of possible path sums ending at node u with i edges
dp = [defaultdict(set) for _ in range(n)]
for u, v, w in edges:
graph[u].append((v, w))
for u in range(n):
dp[u][0].add(0) # zero edges = sum 0
for i in range(k):
for u in range(n):
for currSum in dp[u][i]:
for v, w in graph[u]:
newSum = currSum + w
if newSum < t:
dp[v][i + 1].add(newSum)
ans = -1
for u in range(n):
if k in dp[u]:
ans = max(ans, max(dp[u][k]))
return ans
// Accepted solution for LeetCode #3543: Maximum Weighted K-Edge Path
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3543: Maximum Weighted K-Edge Path
// class Solution {
// public int maxWeight(int n, int[][] edges, int k, int t) {
// List<Pair<Integer, Integer>>[] graph = new List[n];
// // dp[i][j] := the set of possible path sums ending at node i with j edges
// Map<Integer, Set<Integer>>[] dp = new Map[n];
//
// for (int u = 0; u < n; ++u) {
// graph[u] = new ArrayList<>();
// dp[u] = new HashMap<>();
// }
//
// for (int[] edge : edges) {
// final int u = edge[0];
// final int v = edge[1];
// final int w = edge[2];
// graph[u].add(new Pair<>(v, w));
// }
//
// for (int u = 0; u < n; ++u) {
// dp[u].putIfAbsent(0, new HashSet<>());
// dp[u].get(0).add(0); // zero edges = sum 0
// }
//
// for (int i = 0; i < k; ++i)
// for (int u = 0; u < n; ++u)
// if (dp[u].containsKey(i))
// for (final int currSum : dp[u].get(i))
// for (Pair<Integer, Integer> pair : graph[u]) {
// final int v = pair.getKey();
// final int w = pair.getValue();
// final int newSum = currSum + w;
// if (newSum < t) {
// dp[v].putIfAbsent(i + 1, new HashSet<>());
// dp[v].get(i + 1).add(newSum);
// }
// }
//
// int ans = -1;
//
// for (int u = 0; u < n; ++u)
// if (dp[u].containsKey(k))
// for (final int sum : dp[u].get(k))
// ans = Math.max(ans, sum);
//
// return ans;
// }
// }
// Accepted solution for LeetCode #3543: Maximum Weighted K-Edge Path
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3543: Maximum Weighted K-Edge Path
// class Solution {
// public int maxWeight(int n, int[][] edges, int k, int t) {
// List<Pair<Integer, Integer>>[] graph = new List[n];
// // dp[i][j] := the set of possible path sums ending at node i with j edges
// Map<Integer, Set<Integer>>[] dp = new Map[n];
//
// for (int u = 0; u < n; ++u) {
// graph[u] = new ArrayList<>();
// dp[u] = new HashMap<>();
// }
//
// for (int[] edge : edges) {
// final int u = edge[0];
// final int v = edge[1];
// final int w = edge[2];
// graph[u].add(new Pair<>(v, w));
// }
//
// for (int u = 0; u < n; ++u) {
// dp[u].putIfAbsent(0, new HashSet<>());
// dp[u].get(0).add(0); // zero edges = sum 0
// }
//
// for (int i = 0; i < k; ++i)
// for (int u = 0; u < n; ++u)
// if (dp[u].containsKey(i))
// for (final int currSum : dp[u].get(i))
// for (Pair<Integer, Integer> pair : graph[u]) {
// final int v = pair.getKey();
// final int w = pair.getValue();
// final int newSum = currSum + w;
// if (newSum < t) {
// dp[v].putIfAbsent(i + 1, new HashSet<>());
// dp[v].get(i + 1).add(newSum);
// }
// }
//
// int ans = -1;
//
// for (int u = 0; u < n; ++u)
// if (dp[u].containsKey(k))
// for (final int sum : dp[u].get(k))
// ans = Math.max(ans, sum);
//
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.