Minimum cost to merge numbers from 1 to N | Java program for the above approach ; 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
import java . util . * ; class GFG { static int GetMinCost ( int N ) { PriorityQueue < Integer > pq ; pq = new PriorityQueue < > ( ) ; for ( int i = 1 ; i <= N ; i ++ ) { pq . add ( i ) ; } int cost = 0 ; while ( pq . size ( ) > 1 ) { int mini = pq . remove ( ) ; int secondmini = pq . remove ( ) ; int current = mini * secondmini ; cost += current ; pq . add ( current ) ; } return cost ; } public static void main ( String args [ ] ) { int N = 5 ; System . out . println ( GetMinCost ( N ) ) ; } }