Minimum cost to merge numbers from 1 to N | Function returns the minimum cost ; Min Heap representation ; Add all elements to heap ; First minimum ; Second minimum ; Multiply them ; Add to the cost ; Push the product into the heap again ; Return the optimal cost ; Driver code
function GetMinCost ( N ) { let pq = [ ] ; for ( let i = 1 ; i <= N ; i ++ ) { pq . push ( i ) ; } pq . sort ( function ( a , b ) { return a - b } ) ; let cost = 0 ; while ( pq . length > 1 ) { let mini = pq [ 0 ] ; pq . shift ( ) ; let secondmini = pq [ 0 ] ; pq . shift ( ) ; let current = mini * secondmini ; cost += current ; pq . push ( current ) ; pq . sort ( function ( a , b ) { return a - b } ) ; } return cost ; } let N = 5 ; document . write ( GetMinCost ( N ) ) ;