Maximum Weighted K-Edge Path - Problem
Maximum Weighted K-Edge Path in DAG
You're an explorer navigating through a Directed Acyclic Graph (DAG) representing a network of cities connected by weighted roads. Your mission is to find the most valuable route that satisfies specific constraints.
Given:
- A DAG with
nnodes (cities) labeled from0ton-1 - An array
edgeswhereedges[i] = [u_i, v_i, w_i]represents a directed road from cityu_ito cityv_iwith valuew_i - Two integers:
k(exact number of roads to travel) andt(strict upper bound on total value)
Your Goal: Find the maximum possible sum of edge weights for any path that:
- Contains exactly
kedges - Has total weight strictly less than
t
Return the maximum sum, or -1 if no valid path exists.
Example: If you need exactly 3 roads with total value < 100, and you find paths with values [85, 92, 78], return 92 as it's the highest valid sum.
Input & Output
example_1.py β Basic Path Finding
$
Input:
n = 4, edges = [[0,1,5],[1,2,3],[2,3,2]], k = 2, t = 10
βΊ
Output:
8
π‘ Note:
The path 0β1β2 uses exactly 2 edges with total weight 5+3=8, which is less than t=10. This is the maximum possible sum meeting both constraints.
example_2.py β No Valid Path
$
Input:
n = 3, edges = [[0,1,10],[1,2,15]], k = 2, t = 20
βΊ
Output:
-1
π‘ Note:
The only 2-edge path 0β1β2 has weight 10+15=25, which is not less than t=20. No valid path exists.
example_3.py β Multiple Valid Paths
$
Input:
n = 4, edges = [[0,1,3],[0,2,7],[1,3,4],[2,3,1]], k = 2, t = 10
βΊ
Output:
8
π‘ Note:
Two valid paths exist: 0β1β3 (weight=7) and 0β2β3 (weight=8). Return 8 as it's the maximum.
Constraints
- 2 β€ n β€ 1000 (number of nodes)
- 0 β€ edges.length β€ 2000 (number of edges)
- edges[i].length == 3 (each edge has source, destination, weight)
- 0 β€ ui, vi β€ n - 1 (valid node indices)
- 1 β€ wi, t β€ 104 (positive weights and threshold)
- 1 β€ k β€ 1000 (path length constraint)
- The graph is a Directed Acyclic Graph (DAG)
Visualization
Tap to expand
Understanding the Visualization
1
ποΈ Survey the Ruins
Map out all bridges and their treasure values, noting that paths flow in one direction only (DAG structure)
2
π Plan Your Routes
Create a strategy table tracking maximum treasure at each location after crossing exactly i bridges
3
β‘ Execute Layer by Layer
Build up solutions incrementally: if you know best treasure after i bridges, compute best after i+1 bridges
4
π Find the Optimal Path
Among all routes with exactly k bridges and treasure < t, select the one with maximum treasure
Key Takeaway
π― Key Insight: Dynamic Programming lets us build optimal solutions incrementally - if we know the best treasure possible after i bridges, we can efficiently compute the best after i+1 bridges by extending each known solution.
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code