Skip to content

Commit 7fc86ea

Browse files
authoredApr 9, 2023
Create 1857-largest-color-value-in-a-directed-graph.kt
1 parent 3bb4abf commit 7fc86ea

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution {
2+
fun largestPathValue(colors: String, edges: Array<IntArray>): Int {
3+
val adj = HashMap<Int, ArrayList<Int>>()
4+
for ((from, to) in edges)
5+
adj[from] = adj.getOrDefault(from, ArrayList<Int>()).apply{this.add(to)}
6+
7+
val visited = HashSet<Int>()
8+
val path = HashSet<Int>()
9+
val count = Array(colors.length){IntArray(26)}
10+
11+
fun dfs(node: Int): Int {
12+
if (node in path)
13+
return Integer.MAX_VALUE
14+
if (node in visited)
15+
return 0
16+
17+
visited.add(node)
18+
path.add(node)
19+
20+
val colorIndex = colors[node] - 'a'
21+
count[node][colorIndex] = 1
22+
23+
adj[node]?.forEach{ nei ->
24+
if (dfs(nei) == Integer.MAX_VALUE)
25+
return Integer.MAX_VALUE
26+
(0 until 26).forEach{ c ->
27+
count[node][c] = maxOf(
28+
count[node][c],
29+
count[nei][c] + if(c == colorIndex) 1 else 0
30+
)
31+
}
32+
}
33+
34+
path.remove(node)
35+
return count[node].max()!!
36+
}
37+
38+
var res = 0
39+
for (i in 0 until colors.length) {
40+
res = maxOf(res, dfs(i))
41+
}
42+
43+
return if(res == Integer.MAX_VALUE) -1 else res
44+
}
45+
}

0 commit comments

Comments
 (0)