There is an undirected graph with n nodes numbered from 0 to n - 1 (inclusive). You are given a 0-indexed integer arrayvalues where values[i] is the value of the ith node. You are also given a 0-indexed 2D integer arrayedges, where each edges[j] = [uj, vj, timej] indicates that there is an undirected edge between the nodes uj and vj, and it takes timej seconds to travel between the two nodes.
Finally, you are given an integer maxTime.
A valid path in the graph is any path that starts at node 0, ends at node 0, and takes at most maxTime seconds to complete. You may visit the same node multiple times. The quality of a valid path is the sum of the values of the unique nodes visited in the path (each node's value is added at most once to the sum).
Return the maximum quality of a valid path.
Note: There are at most four edges connected to each node.
💡 Note:Optimal path: 0 → 3 → 2 → 3 → 0. This visits unique nodes {0, 3, 2} with quality 0+43+10=53 in time 10+1+1+10=22 ≤ 25. Other paths like visiting both nodes 1 and 3 would require at least 40 time units (0→1→0→3→0 or 0→3→0→1→0), exceeding maxTime=25.
💡 Note:Can do 0 → 1 → 0 (quality = 1+2 = 3, time = 20) then 0 → 3 → 0 (adds +4, time +20 = 40 > 30). Or single trip 0 → 3 → 0 (quality = 1+4 = 5, time = 20). Or 0 → 1 → 0 → 3 → 0 would be time 40 > 30. Best single path: 0 → 1 → 0 = 3 (time 20), then can't do more. Wait, what about 0 → 1 → 2 → 1 → 0? Time = 10+10+10+10 = 40 > 30. Try 0 → 3 → 0 → 1 → 0? Time = 10+10+10+10 = 40 > 30. Actually, 0 → 1 → 0 → 3 → 0 impossible since we'd need 40 time but have 30. Best is either 0 → 1 → 0 (quality 3, time 20) or 0 → 3 → 0 (quality 5, time 20). Answer should be 5. But wait, we visit {0,3} so quality = values[0] + values[3] = 1 + 4 = 5. Hmm, let me reconsider the example. Maybe there's a better path I'm missing.
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 key insight is to use backtracking DFS to explore all possible round-trip paths while tracking unique visited nodes. The optimal approach uses path pruning to avoid impossible routes. Time: O(4^k), Space: O(n + maxTime) where k is the effective search depth after pruning.
Common Approaches
✓
Brute Force DFS
⏱️ Time: O(4^maxTime)
Space: O(maxTime)
Use depth-first search to explore every possible path that starts at node 0, ends at node 0, and doesn't exceed maxTime. Track visited nodes to calculate quality correctly.
Optimized Backtracking
⏱️ Time: O(4^k)
Space: O(n + maxTime)
Enhanced DFS that prunes paths early when they can't lead to better solutions or when time constraints make it impossible to return to start.
Brute Force DFS — Algorithm Steps
Build adjacency list from edges
DFS from node 0 tracking current time and visited nodes
When back at node 0, update maximum quality
Backtrack to try all possibilities
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Build Graph
Create adjacency list from edges
2
DFS Search
Recursively explore all paths from node 0
3
Track Quality
Sum values of unique visited nodes
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX_N 1000
#define MAX_E 4001
#define INF 0x3f3f3f3f
typedef struct Edge { int to, t; struct Edge* next; } Edge;
static Edge pool[MAX_E * 2];
static int poolIdx;
static Edge* graph[MAX_N];
void addEdge(int u, int v, int t) {
Edge* a = &pool[poolIdx++]; a->to=v; a->t=t; a->next=graph[u]; graph[u]=a;
Edge* b = &pool[poolIdx++]; b->to=u; b->t=t; b->next=graph[v]; graph[v]=b;
}
static int dist[MAX_N];
static int n;
typedef struct { int d, node; } Item;
typedef struct { Item* data; int sz, cap; } Heap;
static void hpush(Heap* h, Item x) {
if (h->sz == h->cap) { h->cap *= 2; h->data = realloc(h->data, h->cap * sizeof(Item)); }
h->data[h->sz++] = x;
int i = h->sz - 1;
while (i > 0) {
int p = (i-1)/2;
if (h->data[p].d <= h->data[i].d) break;
Item tmp = h->data[p]; h->data[p] = h->data[i]; h->data[i] = tmp; i = p;
}
}
static Item hpop(Heap* h) {
Item ret = h->data[0];
h->data[0] = h->data[--h->sz];
int i = 0;
for (;;) {
int l=2*i+1, r=2*i+2, m=i;
if (l < h->sz && h->data[l].d < h->data[m].d) m = l;
if (r < h->sz && h->data[r].d < h->data[m].d) m = r;
if (m == i) break;
Item tmp = h->data[i]; h->data[i] = h->data[m]; h->data[m] = tmp; i = m;
}
return ret;
}
static void dijkstra(void) {
memset(dist, 0x3f, n * sizeof(int));
dist[0] = 0;
Heap h; h.cap = 64; h.sz = 0; h.data = malloc(h.cap * sizeof(Item));
hpush(&h, (Item){0, 0});
while (h.sz > 0) {
Item cur = hpop(&h);
if (cur.d > dist[cur.node]) continue;
for (Edge* e = graph[cur.node]; e; e = e->next) {
int nd = dist[cur.node] + e->t;
if (nd < dist[e->to]) { dist[e->to] = nd; hpush(&h, (Item){nd, e->to}); }
}
}
free(h.data);
}
static int nodeVal[MAX_N];
static bool visited[MAX_N];
static int maxQ;
static void dfs(int node, int timeLeft, int quality) {
if (node == 0 && quality > maxQ) maxQ = quality;
for (Edge* e = graph[node]; e; e = e->next) {
int v = e->to, t = e->t;
if (t > timeLeft) continue;
if (dist[v] > timeLeft - t) continue;
int bonus = 0;
if (!visited[v]) { visited[v] = true; bonus = nodeVal[v]; }
dfs(v, timeLeft - t, quality + bonus);
if (bonus) visited[v] = false;
}
}
static int solve(int* vals, int valsSize, int edges[][3], int edgesSize, int maxTime) {
n = valsSize;
poolIdx = 0;
memset(graph, 0, sizeof(graph));
memset(visited, 0, n * sizeof(bool));
for (int i = 0; i < n; i++) nodeVal[i] = vals[i];
for (int i = 0; i < edgesSize; i++) addEdge(edges[i][0], edges[i][1], edges[i][2]);
dijkstra();
maxQ = vals[0];
visited[0] = true;
dfs(0, maxTime, vals[0]);
return maxQ;
}
static int parseArr(const char* s, int* out) {
int cnt = 0;
while (*s && *s != '[') s++;
if (*s) s++;
while (*s) {
while (*s == ' ' || *s == '\t') s++;
if (*s == ']' || !*s) break;
char* end;
out[cnt++] = (int)strtol(s, &end, 10);
s = end;
while (*s == ',' || *s == ' ') s++;
}
return cnt;
}
static int parse2D(const char* s, int out[][3]) {
int cnt = 0;
while (*s && *s != '[') s++;
if (*s) s++;
while (*s) {
while (*s == ' ' || *s == ',' || *s == '\t') s++;
if (*s == ']' || !*s) break;
if (*s == '[') {
s++;
for (int c = 0; c < 3; c++) {
while (*s == ' ') s++;
char* end;
out[cnt][c] = (int)strtol(s, &end, 10);
s = end;
while (*s == ',' || *s == ' ') s++;
}
while (*s && *s != ']') s++;
if (*s) s++;
cnt++;
}
}
return cnt;
}
int main(void) {
static char line[1 << 16];
static int vals[MAX_N];
static int edges[MAX_E][3];
int edgesSize = 0, valsSize = 0, maxTime = 0;
while (fgets(line, sizeof(line), stdin)) {
line[strcspn(line, "\n")] = 0;
char* t = line;
while (*t == ' ' || *t == '\t') t++;
if (!*t) continue;
if (strncmp(t, "[[", 2) == 0 || strcmp(t, "[]") == 0)
edgesSize = parse2D(t, edges);
else if (*t == '[')
valsSize = parseArr(t, vals);
else if (*t >= '0' && *t <= '9')
maxTime = (int)strtol(t, NULL, 10);
}
printf("%d\n", solve(vals, valsSize, edges, edgesSize, maxTime));
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(4^maxTime)
In worst case, we can make 4 choices at each step for maxTime steps
n
2n
✓ Linear Growth
Space Complexity
O(maxTime)
Recursion depth limited by maxTime and visited set
n
2n
⚡ Linearithmic Space
23.5K Views
MediumFrequency
~25 minAvg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.