Minimize cost of placing tiles of dimensions 2 * 1 over a Matrix | Function to find the minimum cost in placing N tiles in a grid M [ ] [ ] ; Stores the minimum profit after placing i tiles ; Traverse the grid [ ] [ ] ; Update the orig_cost ; Traverse over the range [ 2 , N ] ; Place tiles horizentally or vertically ; Print the answer ; Driver Code
function tile_placing ( grid , N ) { let dp = new Array ( N + 5 ) ; dp . fill ( 0 ) ; let orig_cost = 0 ; for ( let i = 0 ; i < 2 ; i ++ ) { for ( let j = 0 ; j < N ; j ++ ) { orig_cost += grid [ i ] [ j ] ; } } dp [ 0 ] = 0 ; dp [ 1 ] = Math . abs ( grid [ 0 ] [ 0 ] - grid [ 1 ] [ 0 ] ) ; for ( let i = 2 ; i <= N ; i ++ ) { dp [ i ] = Math . max ( dp [ i - 1 ] + Math . abs ( grid [ 0 ] [ i - 1 ] - grid [ 1 ] [ i - 1 ] ) , dp [ i - 2 ] + Math . abs ( grid [ 0 ] [ i - 2 ] - grid [ 0 ] [ i - 1 ] ) + Math . abs ( grid [ 1 ] [ i - 2 ] - grid [ 1 ] [ i - 1 ] ) ) ; } document . write ( ( orig_cost - dp [ N ] ) + " " ) ; } let M = [ [ 7 , 5 , 1 , 3 ] , [ 8 , 6 , 0 , 2 ] ] ; let N = M [ 0 ] . length ; tile_placing ( M , N ) ;