LeetCode #3543 — MEDIUM

Maximum Weighted K-Edge Path

Move from brute-force thinking to an efficient approach using hash map strategy.

Solve on LeetCode
The Problem

Problem Statement

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.

Example 1:

Input: n = 3, edges = [[0,1,1],[1,2,2]], k = 2, t = 4

Output: 3

Explanation:

  • The only path with k = 2 edges is 0 -> 1 -> 2 with weight 1 + 2 = 3 < t.
  • Thus, the maximum possible sum of weights less than t is 3.

Example 2:

Input: n = 3, edges = [[0,1,2],[0,2,3]], k = 1, t = 3

Output: 2

Explanation:

  • There are two paths with k = 1 edge:
    • 0 -> 1 with weight 2 < t.
    • 0 -> 2 with weight 3 = t, which is not strictly less than t.
  • Thus, the maximum possible sum of weights less than t is 2.

Example 3:

Input: n = 3, edges = [[0,1,6],[1,2,8]], k = 1, t = 6

Output: -1

Explanation:

  • There are two paths with k = 1 edge:
    • 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.
  • Since there is no path with sum of weights strictly less than t, the answer is -1.

Constraints:

  • 1 <= n <= 300
  • 0 <= edges.length <= 300
  • edges[i] = [ui, vi, wi]
  • 0 <= ui, vi < n
  • ui != vi
  • 1 <= wi <= 10
  • 0 <= k <= 300
  • 1 <= t <= 600
  • The input graph is guaranteed to be a DAG.
  • There are no duplicate edges.
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem 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.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Hash Map · Dynamic Programming

Example 1

3
[[0,1,1],[1,2,2]]
2
4

Example 2

3
[[0,1,2],[0,2,3]]
1
3

Example 3

3
[[0,1,6],[1,2,8]]
1
6
Step 02

Core Insight

What unlocks the optimal approach

  • Use Dynamic Programming
  • How many paths and path sums are possible? Can we maintain the pathSums for a given path length ending at a particular node in a set?
  • The set <code>dp[i][j]</code> contains all possible path weights that end at node <code>i</code>, have total weight less than <code>T</code>, and consist of exactly <code>j</code> edges
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

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;
  }
}
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n × m)
Space
O(n × m)

Approach Breakdown

RECURSIVE
O(2ⁿ) time
O(n) space

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.

DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space

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.

Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

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.

State misses one required dimension

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.