Connect n ropes with minimum cost | Java program to connect n ropes with minimum cost ; Create a priority queue ; Initialize result ; While size of priority queue is more than 1 ; Extract shortest two ropes from pq ; Connect the ropes : update result and insert the new rope to pq ; Driver program to test above function
import java . util . * ; class ConnectRopes { static int minCost ( int arr [ ] , int n ) { PriorityQueue < Integer > pq = new PriorityQueue < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { pq . add ( arr [ i ] ) ; } int res = 0 ; while ( pq . size ( ) > 1 ) { int first = pq . poll ( ) ; int second = pq . poll ( ) ; res += first + second ; pq . add ( first + second ) ; } return res ; } public static void main ( String args [ ] ) { int len [ ] = { 4 , 3 , 2 , 6 } ; int size = len . length ; System . out . println ( " Total ▁ cost ▁ for ▁ connecting " + " ▁ ropes ▁ is ▁ " + minCost ( len , size ) ) ; } }