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