Maximum Path Quality of a Graph - Problem
You're a treasure hunter exploring an undirected graph representing a network of caves. Each cave has a unique treasure value, and you must find the most valuable round trip starting and ending at cave 0.
The Challenge:
- Start at cave 0 and return to cave 0 within
maxTimeseconds - You can visit the same cave multiple times, but each cave's treasure only counts once toward your total quality
- Travel between caves takes time based on the edge weights
- Each cave connects to at most 4 other caves
Input: An array values where values[i] is the treasure value of cave i, a 2D array edges where each edges[j] = [u, v, time] represents a bidirectional tunnel taking time seconds, and maxTime constraint.
Goal: Return the maximum quality (sum of unique cave values) achievable in a valid round trip.
Input & Output
example_1.py β Basic Path
$
Input:
values = [0,32,10,43], edges = [[0,1,10],[1,2,15],[0,3,10]], maxTime = 49
βΊ
Output:
75
π‘ Note:
Optimal path: 0 -> 1 -> 2 -> 1 -> 0. Time: 10+15+15+10 = 50 > 49, so try 0 -> 3 -> 0 -> 1 -> 0. Time: 10+10+10+10 = 40. Quality: values[0]+values[3]+values[1] = 0+43+32 = 75
example_2.py β Time Constraint
$
Input:
values = [5,10,15,20], edges = [[0,1,10],[1,2,10],[0,3,10]], maxTime = 30
βΊ
Output:
25
π‘ Note:
Can visit 0 -> 1 -> 0 -> 3 -> 0 in exactly 30 time units. Quality: values[0]+values[1]+values[3] = 5+10+20 = 35. But optimal is 0 -> 3 -> 0 with quality 25
example_3.py β Single Node
$
Input:
values = [1,2,3,4], edges = [[0,1,40],[1,2,50],[1,3,30]], maxTime = 50
βΊ
Output:
3
π‘ Note:
Can only visit node 0 and return within time limit, so quality is values[0] = 1. Wait, we can go 0->1->0 in 80 time, exceeding limit. Only node 0 accessible, quality = 1. Actually 0->3->1->0 might work if there's edge 1-3
Constraints
- n == values.length
- 1 β€ n β€ 1000
- 0 β€ values[i] β€ 108
- 0 β€ edges.length β€ 2000
- edges[j].length == 3
- 0 β€ uj, vj β€ n - 1
- 10 β€ timej, maxTime β€ 100
- There are at most four edges connected to each node
- The graph may not be connected
Visualization
Tap to expand
Understanding the Visualization
1
Start Exploration
Begin at cave 0 with full time budget and empty treasure collection
2
Branch and Bound
Explore each tunnel, tracking time spent and treasures collected
3
Quality Calculation
When returning to cave 0, calculate total treasure value from unique caves visited
4
Optimal Path Found
Compare all valid round trips to find maximum treasure value
Key Takeaway
π― Key Insight: Use backtracking with time-based pruning to explore all valid round trips. The constraint of at most 4 edges per node keeps the search space manageable.
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code