Maximum number of plates that can be placed from top to bottom in increasing order of size | Recursive function to count and return the max number of plates that can be placed ; If no plate remains ; If length and width of previous plate exceeds that of the current plate ; Calculate including the plate ; Calculate excluding the plate ; Otherwise ; Calculate only excluding the plate ; Driver code ; Sorting plates in decreasing order of area ; Assuming first plate to be of maximum size
function countPlates ( plates , lastLength , lastWidth , i , n ) { if ( i == n ) return 0 ; var taken = 0 , notTaken = 0 ; if ( lastLength > plates [ i ] [ 0 ] && lastWidth > plates [ i ] [ 1 ] ) { taken = 1 + countPlates ( plates , plates [ i ] [ 0 ] , plates [ i ] [ 1 ] , i + 1 , n ) ; notTaken = countPlates ( plates , lastLength , lastWidth , i + 1 , n ) ; } else notTaken = countPlates ( plates , lastLength , lastWidth , i + 1 , n ) ; return Math . max ( taken , notTaken ) ; } var plates = [ [ 6 , 4 ] , [ 5 , 7 ] , [ 1 , 2 ] , [ 3 , 3 ] , [ 7 , 9 ] ] ; var n = plates . length ; plates . sort ( ( v1 , v2 ) => v2 [ 0 ] * v2 [ 1 ] - v1 [ 0 ] * v1 [ 1 ] ) ; var lastLength = 1000000000 ; var lastWidth = 1000000000 ; document . write ( countPlates ( plates , lastLength , lastWidth , 0 , n ) ) ;