[LeetCode] Node With Highest Edge Score

2374. Node With Highest Edge Score

You are given a directed graph with n nodes labeled from 0 to n - 1, where each node has exactly one outgoing edge.

The graph is represented by a given 0-indexed integer array edges of length n, where edges[i] indicates that there is a directed edge from node i to node edges[i].

The edge score of a node i is defined as the sum of the labels of all the nodes that have an edge pointing to i.

Return the node with the highest edge score. If multiple nodes have the same edge score, return the node with the smallest index.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int edgeScore(vector<int>& edges) {
unordered_map<int, long long> score;
long long ma = -1, res = -1;
for(int i = 0; i < edges.size(); i++) {
score[edges[i]] += i;
if(score[edges[i]] > ma) {
ma = score[edges[i]];
res = edges[i];
} else if(score[edges[i]] == ma) {
res = min(res, 1ll * edges[i]);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/14/PS/Codeforces/node-with-highest-edge-score/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.