You are given an undirected graph with n nodes numbered 0 to n - 1. The array values holds each node's value: values[i] is the value of node i. Each entry edges[j] = [u, v, t] is an undirected edge between nodes u and v that takes t seconds to travel in either direction. You are also given an integer max_time.
A valid path starts at node 0, ends at node 0, and takes at most max_time seconds in total. It may visit the same node, and cross the same edge, any number of times. The quality of a valid path is the sum of the values of the distinct nodes it visits. Each node's value counts at most once, however many times the path passes through it.
Return the maximum quality of a valid path. Every node has at most four edges.
Function Signature
def maximal_path_quality(values: list[int], edges: list[list[int]], max_time: int) -> int:
Rules
-
The path that never leaves node
0
is valid and has quality
values[0]
, so the answer is at least
values[0]
.
-
The travel time of a path is the sum of the times of the edges it crosses, counting an edge again each time it is crossed.
-
The graph may be disconnected. Nodes that cannot be reached from node
0
contribute nothing.
Constraints
-
n == len(values)
-
1 <= n <= 1000
-
0 <= values[i] <= 10^8
-
0 <= len(edges) <= 2000
-
len(edges[j]) == 3
-
0 <= u < v <= n - 1
-
10 <= t, max_time <= 100
-
All pairs
[u, v]
are unique.
-
At most four edges are connected to each node.
Examples
Input: values = [0,32,10,43], edges = [[0,1,10],[1,2,15],[0,3,10]], max_time = 49
Output: 75
The path 0 -> 1 -> 0 -> 3 -> 0 takes 40 seconds and visits nodes 0, 1 and 3, for a quality of 0 + 32 + 43 = 75. Collecting node 2 needs at least 0 -> 1 -> 2 -> 1 -> 0, which takes 50 seconds and is over the limit.
Input: values = [5,10,15,20], edges = [[0,1,10],[1,2,10],[0,3,10]], max_time = 30
Output: 25
The path 0 -> 3 -> 0 takes 20 seconds and scores 5 + 20 = 25. Visiting nodes 1 and 3 together takes 40 seconds, and 0 -> 1 -> 0 alone scores only 15.
Input: values = [1,2,3,4], edges = [[0,1,10],[1,2,11],[2,3,12],[1,3,13]], max_time = 50
Output: 7
The path 0 -> 1 -> 3 -> 1 -> 0 takes 10 + 13 + 13 + 10 = 46 seconds and collects 1 + 2 + 4 = 7. Any path that visits both node 2 and node 3 needs at least 56 seconds.