Minimum cost to merge numbers from 1 to N | C # program to find the 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
using System ; using System . Collections . Generic ; class GFG { static int GetMinCost ( int N ) { List < int > pq = new List < int > ( ) ; for ( int i = 1 ; i <= N ; i ++ ) { pq . Add ( i ) ; } int cost = 0 ; pq . Sort ( ) ; while ( pq . Count > 1 ) { int mini = pq [ 0 ] ; pq . RemoveAt ( 0 ) ; int secondmini = pq [ 0 ] ; pq . RemoveAt ( 0 ) ; int current = mini * secondmini ; cost += current ; pq . Add ( current ) ; pq . Sort ( ) ; } return cost ; } static void Main ( ) { int N = 5 ; Console . WriteLine ( GetMinCost ( N ) ) ; } }