@@ -37,9 +37,6 @@ class MinHeap {
3737 while ( true ) {
3838 const left = 2 * index + 1 ;
3939 const right = 2 * index + 2 ;
40-
41- let min = Math . min ( this . heap [ left ] , this . heap [ right ] ) ;
42- [ this . heap [ index ] , min ] = [ min , this . heap [ index ] ] ;
4340 let smallest = index ;
4441
4542 if ( left < length && this . heap [ left ] < this . heap [ smallest ] ) {
@@ -56,17 +53,18 @@ class MinHeap {
5653 this . heap [ smallest ] ,
5754 this . heap [ index ] ,
5855 ] ;
56+
5957 index = smallest ;
6058 }
6159 }
6260
6361 least ( ) {
6462 return this . heap [ 0 ] ;
6563 }
66- }
6764
68- function calculateScovile ( num1 , num2 ) {
69- return num1 + num2 * 2 ;
65+ size ( ) {
66+ return this . heap . length ;
67+ }
7068}
7169
7270function solution ( scoville , K ) {
@@ -75,6 +73,16 @@ function solution(scoville, K) {
7573
7674 const minHeap = new MinHeap ( ) ;
7775 scoville . forEach ( ( s ) => minHeap . push ( s ) ) ;
76+ let mixCount = 0 ;
77+ while ( minHeap . size ( ) > 1 && minHeap . least ( ) < K ) {
78+ const first = minHeap . pop ( ) ;
79+ const second = minHeap . pop ( ) ;
80+ const newScoville = first + second * 2 ;
81+ minHeap . push ( newScoville ) ;
82+ mixCount ++ ;
83+ }
84+
85+ return minHeap . least ( ) >= K ? mixCount : - 1 ;
7886}
7987
8088console . log ( solution ( [ 1 , 2 , 3 , 9 , 10 , 12 ] , 7 ) ) ;
0 commit comments