2065. Maximum Path Quality of a Graph

10 <= timej, maxTime <= 100, so at most 10 nodes
There are at most 4 edges connected to each node.
so

T: O(4^10)
S: O(n)
class Solution {
    private int result = 0;
    public int maximalPathQuality(int[] values, int[][] edges, int maxTime) {
        int n = values.length;
        List<int[]>[] graph = new ArrayList[n];
        for (int i = 0; i < n; i++) {
            graph[i] = new ArrayList<>();
        }
        for (int[] edge : edges) {
            int u = edge[0];
            int v = edge[1];
            int t = edge[2];
            graph[u].add(new int[]{v, t});
            graph[v].add(new int[]{u, t});
        }
        
        int[] visited = new int[n];
        visited[0] = 1;
        dfs(0, values[0], 0, values, graph, maxTime, visited);
        return result;
    }
    private void dfs(int curNode, int curValue, int curTime, int[] values, List<int[]>[] graph, int maxTime, int[] visited) {
        if (curTime > maxTime) {
            return;
        }
        if (curNode == 0) {
            result = Math.max(curValue, result);
        }
        for (int[] nodes : graph[curNode]) {
            int nextNode = nodes[0];
            int time = nodes[1];
            visited[nextNode]++;
            dfs(nextNode, curValue + (visited[nextNode] == 1 ? values[nextNode] : 0), curTime + time, values, graph, maxTime, visited);
            visited[nextNode]--;
        }
    }
}

/*
10 <= timej, maxTime <= 100, so at most 10 nodes
There are at most four edges connected to each node.
so

T: O(4^10)
S: O(n)
*/

follow up:

if no travel_time โ‰ฅ 10? use DP I think

Last updated