A weighted directed graph has n nodes labeled 0 to n - 1. Each entry of edges is [from_i, to_i, cost_i, time_i]: a directed edge from node from_i to node to_i with a monetary cost of cost_i and a travel time of time_i.
You have a total budget max_cost. Return the minimum travel time from node 0 to node n - 1 over all paths whose total cost does not exceed max_cost. If no such path exists, return -1.
Function Signature
def min_time_within_budget(n: int, edges: list[list[int]], max_cost: int) -> int:
Rules
-
An edge
[u, v, cost, time]
can only be followed from
u
to
v
.
-
The cost of a path is the sum of its edge costs, and its time is the sum of its edge times.
-
A path is within budget when its total cost is at most
max_cost
. A cost equal to
max_cost
is allowed.
-
Return the smallest time among paths from
0
to
n - 1
that are within budget, or
-1
if there are none.
-
If
n == 1
, node
0
is already the destination and the answer is
0
.
Constraints
-
1 <= n <= 1000
-
0 <= edges.length <= 10000
-
edges[i].length == 4
-
0 <= from_i, to_i < n
-
1 <= cost_i, time_i <= 1000
-
1 <= max_cost <= 10000
-
There are no self-loops and no duplicate edges.
Examples
Input: n = 4, edges = [[0,1,5,2],[0,2,3,6],[1,3,4,3],[2,3,2,4]], max_cost = 10
Output: 5
There are two paths to node 3. Path 0 -> 1 -> 3 costs 9 and takes 5, and path 0 -> 2 -> 3 costs 5 and takes 10. Both fit the budget of 10, so the answer is the faster one, 5.
Input: n = 3, edges = [[0,1,10,1],[0,2,1,5],[2,1,1,2],[1,2,1,2]], max_cost = 3
Output: 5
The destination is node 2. The direct edge 0 -> 2 costs 1 and takes 5. Any route through node 1 starts with the edge 0 -> 1, which alone costs 10 and is over budget, so the answer is 5.
Input: n = 4, edges = [[0,1,1,10],[0,2,1,1],[2,1,5,1],[1,3,1,1]], max_cost = 7
Output: 3
Path 0 -> 1 -> 3 costs 2 and takes 11. Path 0 -> 2 -> 1 -> 3 costs 7 and takes 3, exactly on budget, so the answer is 3. With max_cost = 6 only the first path would fit and the answer would be 11.