|
| 1 | +package problem2050 |
| 2 | + |
| 3 | +/* |
| 4 | +You are given an integer n, which indicates that there are n courses labeled from 1 to n. |
| 5 | +You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that |
| 6 | +course prevCoursej has to be completed before course nextCoursej (prerequisite relationship). |
| 7 | +Furthermore, you are given a 0-indexed integer array time where time[i] denotes |
| 8 | +how many months it takes to complete the (i+1)th course. |
| 9 | +You must find the minimum number of months needed to complete all the courses following these rules: |
| 10 | +You may start taking a course at any time if the prerequisites are met. |
| 11 | +Any number of courses can be taken at the same time. |
| 12 | +Return the minimum number of months needed to complete all the courses. |
| 13 | +Note: The test cases are generated such that it is possible to complete every course |
| 14 | +(i.e., the graph is a directed acyclic graph). |
| 15 | +*/ |
| 16 | + |
| 17 | +func minimumTime(n int, relations [][]int, time []int) int { |
| 18 | + var res int |
| 19 | + // graph[i] represents the courses the i'th course needs |
| 20 | + var graph = make([][]int, n) |
| 21 | + // fTime[i] represesnts the minimal time needed to complete the i'th course |
| 22 | + var fTime = make([]int, n) |
| 23 | + // solve(i) recursively finds the minimal time to complete the i'th course |
| 24 | + var solve func(int) int |
| 25 | + |
| 26 | + // Building the dependency graph |
| 27 | + for _, r := range relations { |
| 28 | + graph[r[1]-1] = append(graph[r[1]-1], r[0]-1) |
| 29 | + } |
| 30 | + |
| 31 | + solve = func(cur int) int { |
| 32 | + var res int |
| 33 | + // If we already found the minimal time, return it |
| 34 | + if fTime[cur] != 0 { |
| 35 | + return fTime[cur] |
| 36 | + } |
| 37 | + |
| 38 | + // Loop over all the course's dependencies |
| 39 | + for _, d := range graph[cur] { |
| 40 | + // Find out their minimal completion time |
| 41 | + dTime := solve(d) |
| 42 | + // Pick the maximum of those times, since you need to finish all of them |
| 43 | + if dTime > res { |
| 44 | + res = dTime |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + // Write to cache |
| 49 | + fTime[cur] = res + time[cur] |
| 50 | + return fTime[cur] |
| 51 | + } |
| 52 | + |
| 53 | + // Loop over all the courses |
| 54 | + for i := range fTime { |
| 55 | + // Find the minimal time for each |
| 56 | + solve(i) |
| 57 | + // Pick the maximum time (the last course that needs to be completed) |
| 58 | + if fTime[i] > res { |
| 59 | + res = fTime[i] |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + return res |
| 64 | +} |
0 commit comments