Minimum Cost to cut a board into squares | method returns minimum cost to break board into m * n squares ; sort the horizontal cost in reverse order ; sort the vertical cost in reverse order ; initialize current width as 1 ; loop until one or both cost array are processed ; increase current horizontal part count by 1 ; increase current vertical part count by 1 ; loop for horizontal array , if remains ; loop for vertical array , if remains ; Driver Code
function minimumCostOfBreaking ( X , Y , m , n ) { let res = 0 ; X . sort ( ) ; X . reverse ( ) ; Y . sort ( ) ; Y . reverse ( ) ; let hzntl = 1 , vert = 1 ; let i = 0 , j = 0 ; while ( i < m && j < n ) { if ( X [ i ] > Y [ j ] ) { res += X [ i ] * vert ; hzntl ++ ; i ++ ; } else { res += Y [ j ] * hzntl ; vert ++ ; j ++ ; } } let total = 0 ; while ( i < m ) total += X [ i ++ ] ; res += total * vert ; total = 0 ; while ( j < n ) total += Y [ j ++ ] ; res += total * hzntl ; return res ; } let m = 6 , n = 4 ; let X = [ 2 , 1 , 3 , 1 , 4 ] ; let Y = [ 4 , 1 , 2 ] ; document . write ( minimumCostOfBreaking ( X , Y , m - 1 , n - 1 ) ) ;