Sum of Areas of Rectangles possible for an array | Function to find area of rectangles ; sorting the array in descending order ; store the final sum of all the rectangles area possible ; temporary variable to store the length of rectangle ; Selecting the length of rectangle so that difference between any two number is 1 only . Here length is selected so flag is set ; flag is set means we have got length of rectangle ; length is set to a [ i + 1 ] so that if a [ i + 1 ] is less than a [ i ] by 1 then also we have the correct chice for length ; incrementing the counter one time more as we have considered a [ i + 1 ] element also so . ; Selecting the width of rectangle so that difference between any two number is 1 only . Here width is selected so now flag is again unset for next rectangle ; area is calculated for rectangle ; flag is set false for another rectangle which we can get from elements in array ; incrementing the counter one time more as we have considered a [ i + 1 ] element also so . ; Driver code
< ? php function MaxTotalRectangleArea ( $ a , $ n ) { rsort ( $ a ) ; $ sum = 0 ; $ flag = false ; $ len ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( ( $ a [ $ i ] == $ a [ $ i + 1 ] or $ a [ $ i ] - $ a [ $ i + 1 ] == 1 ) and ( ! $ flag ) ) { $ flag = true ; $ len = $ a [ $ i + 1 ] ; $ i ++ ; } else if ( ( $ a [ $ i ] == $ a [ $ i + 1 ] or $ a [ $ i ] - $ a [ $ i + 1 ] == 1 ) and ( $ flag ) ) { $ sum = $ sum + $ a [ $ i + 1 ] * $ len ; $ flag = false ; $ i ++ ; } } return $ sum ; } $ a = array ( 10 , 10 , 10 , 10 , 11 , 10 , 11 , 10 , 9 , 9 , 8 , 8 ) ; $ n = count ( $ a ) ; echo MaxTotalRectangleArea ( $ a , $ n ) ; ? >