@@ -56,7 +56,7 @@ const scheduleCourse = (courses) => {
5656 courses . sort ( ( a , b ) => a [ 1 ] - b [ 1 ] )
5757 let res = 0
5858 const n = courses . length
59- const cache = [ ...Array ( n ) ] . map ( ( ) => Array ( courses [ n - 1 ] [ 1 ] ) )
59+ const cache = [ ...Array ( n + 1 ) ] . map ( ( ) => Array ( courses [ n - 1 ] [ 1 ] ) )
6060 return helper ( courses , 0 , 0 , cache )
6161 function helper ( courses , curDay , index , cache ) {
6262 if ( index === n ) {
@@ -75,4 +75,26 @@ const scheduleCourse = (courses) => {
7575 cache [ index ] [ curDay ] = Math . max ( taken , notTaken )
7676 return cache [ index ] [ curDay ]
7777 }
78+ }
79+
80+
81+ // 3)
82+ // https://leetcode.com/problems/course-schedule-iii/discuss/513455/javascript-sort-and-dp-explain-in-comments
83+ /**
84+ * @param {number[][] } courses
85+ * @return {number }
86+ */
87+ const scheduleCourse = ( courses ) => {
88+ if ( ! courses . length ) return 0
89+ courses . sort ( ( [ t1 , d1 ] , [ t2 , d2 ] ) => d2 - d1 )
90+ let arr = Array ( courses . length + 1 ) . fill ( - 1 )
91+ arr [ 0 ] = Number . MAX_SAFE_INTEGER
92+ let maxCount = 0
93+ for ( let [ t , d ] of courses ) {
94+ for ( let i = maxCount + 1 ; i > 0 ; i -- ) {
95+ arr [ i ] = Math . max ( arr [ i ] , Math . min ( arr [ i - 1 ] , d ) - t )
96+ if ( arr [ i ] > - 1 && i > maxCount ) maxCount = i
97+ }
98+ }
99+ return maxCount
78100}
0 commit comments