LeetCode 2242: Maximum Score of a Node Sequence

Problem Description

Explanation

To find the maximum score of a valid node sequence with a length of 4, we can iterate through all possible combinations of 4 nodes and calculate the score for each valid sequence. We can use a set to keep track of the nodes and edges to efficiently check if a sequence is valid. If a sequence is valid, we update the maximum score found so far.

Solutions

class Solution {
    public int maxScore(int[] scores, int[][] edges) {
        int n = scores.length;
        int maxScore = -1;
        Set<Integer> visitedNodes = new HashSet<>();
        Set<String> visitedEdges = new HashSet<>();
        
        for (int i = 0; i < n; i++) {
            visitedNodes.add(i);
            for (int j = 0; j < n; j++) {
                if (i == j) continue;
                for (int k = 0; k < n; k++) {
                    if (j == k || visitedNodes.contains(j) || visitedNodes.contains(k)) continue;
                    for (int l = 0; l < n; l++) {
                        if (k == l || visitedNodes.contains(l)) continue;
                        visitedEdges.clear();
                        visitedEdges.add(i + "-" + j);
                        visitedEdges.add(j + "-" + k);
                        visitedEdges.add(k + "-" + l);
                        visitedEdges.add(i + "-" + k);
                        visitedEdges.add(j + "-" + l);
                        if (visitedEdges.size() == 5) {
                            maxScore = Math.max(maxScore, scores[i] + scores[j] + scores[k] + scores[l]);
                        }
                    }
                }
            }
            visitedNodes.remove(i);
        }
        
        return maxScore;
    }
}

Loading editor...