-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
74 lines (62 loc) · 1.08 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"container/heap"
"fmt"
"sort"
)
func main() {
fmt.Println(scheduleCourse([][]int{{100, 200}, {200, 1300}, {1000, 1250}, {2000, 3200}}))
}
func scheduleCourse(courses [][]int) int {
sort.Slice(courses, func(i, j int) bool {
return courses[i][1] < courses[j][1]
})
pq := &PQ{}
heap.Init(pq)
var (
result int
t int
)
// fmt.Println(courses)
for i := 0; i < len(courses); i++ {
curr := courses[i]
if curr[0] > curr[1] {
continue
}
if t+curr[0] > curr[1] {
last := heap.Pop(pq).(int)
if last < curr[0] {
heap.Push(pq, last)
continue
}
t -= last
result--
}
t += curr[0]
result++
heap.Push(pq, curr[0])
// fmt.Println(t)
}
return result
}
type PQ []int
func (pq PQ) Len() int {
return len(pq)
}
func (pq PQ) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
}
// max-heap
func (pq PQ) Less(i, j int) bool {
return pq[i] > pq[j]
}
func (pq *PQ) Push(x interface{}) {
tmp := x.(int)
*pq = append(*pq, tmp)
}
func (pq *PQ) Pop() interface{} {
n := len(*pq)
tmp := (*pq)[n-1]
*pq = (*pq)[:n-1]
return tmp
}