Maximize the length of upper boundary formed by placing given N rectangles horizontally or vertically | Function to find maximum length of the upper boundary formed by placing each of the rectangles either horizontally or vertically ; Stores the intermediate transition states ; Place the first rectangle horizontally ; Place the first rectangle vertically ; Place horizontally ; Stores the difference in height of current and previous rectangle ; Take maximum out of two options ; Place Vertically ; Stores the difference in height of current and previous rectangle ; Take maximum out two options ; Print maximum of horizontal or vertical alignment of the last rectangle ; Driver Code
function maxBoundary ( N , V ) { let dp = new Array ( N ) . fill ( 0 ) . map ( ( ) => new Array ( 2 ) . fill ( 0 ) ) ; dp [ 0 ] [ 0 ] = V [ 0 ] [ 0 ] ; dp [ 0 ] [ 1 ] = V [ 0 ] [ 1 ] ; for ( let i = 1 ; i < N ; i ++ ) { dp [ i ] [ 0 ] = V [ i ] [ 0 ] ; let height1 = Math . abs ( V [ i - 1 ] [ 1 ] - V [ i ] [ 1 ] ) ; let height2 = Math . abs ( V [ i - 1 ] [ 0 ] - V [ i ] [ 1 ] ) ; dp [ i ] [ 0 ] += Math . max ( height1 + dp [ i - 1 ] [ 0 ] , height2 + dp [ i - 1 ] [ 1 ] ) ; dp [ i ] [ 1 ] = V [ i ] [ 1 ] ; let vertical1 = Math . abs ( V [ i ] [ 0 ] - V [ i - 1 ] [ 1 ] ) ; let vertical2 = Math . abs ( V [ i ] [ 0 ] - V [ i - 1 ] [ 0 ] ) ; dp [ i ] [ 1 ] += Math . max ( vertical1 + dp [ i - 1 ] [ 0 ] , vertical2 + dp [ i - 1 ] [ 1 ] ) ; } document . write ( Math . max ( dp [ N - 1 ] [ 0 ] , dp [ N - 1 ] [ 1 ] ) ) ; } let N = 5 ; let V = [ [ 2 , 5 ] , [ 3 , 8 ] , [ 1 , 10 ] , [ 7 , 14 ] , [ 2 , 5 ] , ] ; maxBoundary ( N , V ) ;