2023-04-09 Daily Challenge
Today I have done leetcode's April LeetCoding Challenge with cpp
.
April LeetCoding Challenge 9
Description
Largest Color Value in a Directed Graph
There is a directed graph of n
colored nodes and m
edges. The nodes are numbered from 0
to n - 1
.
You are given a string colors
where colors[i]
is a lowercase English letter representing the color of the ith
node in this graph (0-indexed). You are also given a 2D array edges
where edges[j] = [aj, bj]
indicates that there is a directed edge from node aj
to node bj
.
A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk
such that there is a directed edge from xi
to xi+1
for every 1 <= i < k
. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path.
Return the largest color value of any valid path in the given graph, or -1
if the graph contains a cycle.
Example 1:
Input: colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]]
Output: 3
Explanation: The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored "a" (red in the above image)
.
Example 2:
Input: colors = "a", edges = [[0,0]] Output: -1 Explanation: There is a cycle from 0 to 0.
Constraints:
n == colors.length
m == edges.length
1 <= n <= 105
0 <= m <= 105
colors
consists of lowercase English letters.0 <= aj, bj < n
Solution
class Solution {
using T = array<int, 26>;
public:
int largestPathValue(string colors, vector<vector<int>>& edges) {
vector<vector<int>> neighbors(colors.size());
vector<int> indegree(colors.size());
for(const auto &edge : edges) {
neighbors[edge[0]].push_back(edge[1]);
indegree[edge[1]] += 1;
}
vector<T> count(colors.size(), T{});
queue<int> q;
for(int i = 0; i < colors.size(); ++i) {
if(!indegree[i]) {
q.push(i);
count[i][colors[i] - 'a'] = 1;
}
}
int answer = 0;
int seen = 0;
while(q.size()) {
int current = q.front();
q.pop();
seen += 1;
answer = max(answer, *max_element(count[current].begin(), count[current].end()));
for(auto neighbor : neighbors[current]) {
for(int i = 0; i < 26; ++i) {
count[neighbor][i] = max(count[neighbor][i], count[current][i] + (i == colors[neighbor] - 'a'));
}
indegree[neighbor] -= 1;
if(!indegree[neighbor]) {
q.push(neighbor);
}
}
}
if(seen < colors.size()) return -1;
return answer;
}
};
// Accepted
// 83/83 cases passed (530 ms)
// Your runtime beats 93.59 % of cpp submissions
// Your memory usage beats 90.6 % of cpp submissions (143.3 MB)