LeetCode Problem Workspace

Maximum Weighted K-Edge Path

Determine the maximum sum of edge weights for a k-edge path in a DAG using state transition dynamic programming efficiently.

category

3

Topics

code_blocks

0

Code langs

hub

3

Related

Practice Focus

Medium · State transition dynamic programming

bolt

Answer-first summary

Determine the maximum sum of edge weights for a k-edge path in a DAG using state transition dynamic programming efficiently.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for State transition dynamic programming

Try AiBox Copilotarrow_forward

This problem requires finding the maximum weighted path of exactly k edges in a directed acyclic graph. Use state transition dynamic programming to track the best sum for each node with a specific number of edges. Hash tables help store intermediate states efficiently, reducing redundant calculations and ensuring a fast solution.

Problem Statement

Given a directed acyclic graph with n nodes labeled from 0 to n-1, represented as a list of edges where each edge has a weight, find a path containing exactly k edges that maximizes the total weight. Each edge is given as [from, to, weight]. You are also given a threshold t, but the path sum may exceed it.

Return the maximum sum of weights for any path of exactly k edges. If no such path exists that meets the k-edge requirement, return -1. The graph contains no duplicate edges and guarantees a DAG structure.

Examples

Example 1

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

Output: 3

Example 2

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

Output: 2

Example 3

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

Output: -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.

Solution Approach

Dynamic Programming Table

Define a DP table dp[node][edges] representing the maximum sum to reach 'node' using 'edges' edges. Initialize dp values with negative infinity except for starting nodes. Update dp entries by iterating through each edge and applying the state transition formula dp[vi][e+1] = max(dp[vi][e+1], dp[ui][e] + wi).

Topological Traversal

Process nodes in topological order to guarantee all predecessors are computed before a node. This ensures that when updating dp for a node with e edges, all necessary states from earlier nodes are already available, preventing incorrect path sums or missing valid paths.

Hash Table Optimization

Use hash tables to store dp[node][edges] instead of dense arrays when many entries are unused. This reduces memory overhead and speeds up updates for sparse graphs, especially when k or n is large, aligning with the state transition dynamic programming pattern efficiently.

Complexity Analysis

Metric Value
Time Depends on the final approach
Space Depends on the final approach

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

What Interviewers Usually Probe

  • You start considering dynamic programming but may overlook edge count as a separate state dimension.
  • The candidate thinks about longest path but misses the exact k-edge requirement.
  • The candidate attempts greedy selection of highest weights without DP, leading to incorrect sums.

Common Pitfalls or Variants

Common pitfalls

  • Forgetting to track the exact number of edges in the path can produce incorrect maximum sums.
  • Processing nodes in arbitrary order may use incomplete predecessor data and fail on DAG paths.
  • Not handling cases where no k-edge path exists, returning 0 or invalid values instead of -1.

Follow-up variants

  • Find the minimum weighted k-edge path instead of the maximum, adjusting DP to track minimum sums.
  • Allow paths of at most k edges, requiring a max over all dp[node][1..k] entries for the final answer.
  • Compute maximum weighted path with additional constraints on node visitation, modifying state to include visited sets.

FAQ

What is the key DP state for Maximum Weighted K-Edge Path?

The key state is dp[node][edges] storing the maximum sum reaching 'node' using exactly 'edges' edges.

Can the maximum path sum exceed threshold t?

Yes, t is informational; the algorithm focuses on maximizing sum for exactly k edges, ignoring threshold limitations.

How to handle graphs where no k-edge path exists?

Return -1 explicitly if no node achieves a valid sum with exactly k edges, as per problem specification.

Why is topological sorting needed in this DP approach?

Topological order ensures all predecessors are processed first, guaranteeing accurate DP updates for each node.

Can hash tables improve performance in this problem?

Yes, storing only used dp[node][edges] entries in hash tables reduces memory and speeds up sparse DAG computations.

terminal

Solution

Solution 1

#### Python3

1
Maximum Weighted K-Edge Path Solution: State transition dynamic programming | LeetCode #3543 Medium