classSolution { funminimumTime(n: Int, relations: Array<IntArray>, time: IntArray): Int { val outCourse = Array(n) { ArrayList<Int>() } val inCourse = IntArray(n) val dp = IntArray(n) { 0 } val topoQueue: Deque<Int> = LinkedList()
for (relation in relations) { outCourse[relation[0] - 1].add(relation[1] - 1) inCourse[relation[1] - 1]++ }
for ((index, value) in inCourse.withIndex()) { if (value == 0) { topoQueue.addLast(index) dp[index] = time[index] } }
while (topoQueue.isNotEmpty()) { val prev = topoQueue.removeFirst() for (next in outCourse[prev]) { dp[next] = Math.max(dp[next], dp[prev] + time[next]) inCourse[next]--
if (inCourse[next] == 0) { topoQueue.addLast(next) } } }