@@ -97,4 +97,61 @@ const scheduleCourse = (courses) => {
9797 }
9898 }
9999 return maxCount
100- }
100+ }
101+
102+
103+ // 4) max heap
104+ /**
105+ * @param {number[][] } courses
106+ * @return {number }
107+ */
108+ const scheduleCourse = ( courses ) => {
109+ let day = 0
110+ const learned = [ ]
111+ courses . sort ( ( a , b ) => a [ 1 ] - b [ 1 ] )
112+ courses . forEach ( ( [ duration , endDay ] ) => {
113+ learned . push ( duration )
114+ buildHeap ( learned )
115+ day += duration
116+ if ( day > endDay ) {
117+ swap ( learned , learned . length - 1 , 0 )
118+ day -= learned . pop ( )
119+ maxHeapify ( learned , learned . length - 1 , 0 )
120+ }
121+ } )
122+ return learned . length
123+ // 创建堆
124+ function buildHeap ( arr ) {
125+ const len = arr . length
126+ const parent = getParent ( len )
127+ for ( let i = parent ; i >= 0 ; i -- ) {
128+ maxHeapify ( arr , len , i )
129+ }
130+ }
131+ // 维护堆
132+ function maxHeapify ( arr , heapSize , index ) {
133+ let larget = index
134+ const [ left , right ] = getChilren ( index )
135+ if ( left < heapSize && arr [ left ] > arr [ index ] ) {
136+ larget = left
137+ }
138+ if ( right < heapSize && arr [ right ] > arr [ larget ] ) {
139+ larget = right
140+ }
141+ if ( larget !== index ) {
142+ swap ( arr , index , larget )
143+ maxHeapify ( arr , heapSize , larget )
144+ }
145+ return arr
146+ }
147+ function getParent ( index ) {
148+ return Math . floor ( ( index - 1 ) / 2 )
149+ }
150+ function getChilren ( index ) {
151+ return [ index * 2 + 1 , index * 2 + 2 ]
152+ }
153+ function swap ( A , a , b ) {
154+ [ A [ a ] , A [ b ] ] = [ A [ b ] , A [ a ] ]
155+ }
156+ }
157+
0 commit comments