630.course-schedule-iii.go 938 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. type array [][]int
  2. func (a array) Len() int { return len(a) }
  3. func (a array) Less(i, j int) bool { return a[i][1] < a[j][1] }
  4. func (a array) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  5. type maxHeap []int
  6. func (h maxHeap) Len() int { return len(h) }
  7. func (h maxHeap) Less(i, j int) bool { return h[j] < h[i] }
  8. func (h maxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
  9. func (h *maxHeap) Push(x interface{}) {
  10. *h = append(*h, x.(int))
  11. }
  12. func (h *maxHeap) Pop() interface{} {
  13. l := h.Len()
  14. x := (*h)[l-1]
  15. *h = (*h)[:l-1]
  16. return x
  17. }
  18. func scheduleCourse(courses [][]int) int {
  19. sort.Sort(array(courses)) // Sort by the deadlines
  20. time, cnt := 0, 0
  21. var h maxHeap
  22. for _, course := range courses {
  23. time += course[0]
  24. heap.Push(&h, course[0])
  25. cnt++
  26. if course[1] < time {
  27. cnt-- // If overdue, remove the course that cost the most time
  28. x := heap.Pop(&h)
  29. time -= x.(int)
  30. }
  31. }
  32. return cnt
  33. }