Sum of Areas of Rectangles possible for an array | CPP code to find sum of all area rectangle possible ; 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 ] a [ i + 1 ] is less than by 1 then also we have the correct choice 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MaxTotalRectangleArea ( int a [ ] , int n ) { sort ( a , a + n , greater < int > ( ) ) ; int sum = 0 ; bool flag = false ; int len ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( a [ i ] == a [ i + 1 ] a [ i ] - a [ i + 1 ] == 1 ) && ( ! flag ) ) { flag = true ; len = a [ i + 1 ] ; i ++ ; } else if ( ( a [ i ] == a [ i + 1 ] a [ i ] - a [ i + 1 ] == 1 ) && ( flag ) ) { sum = sum + a [ i + 1 ] * len ; flag = false ; i ++ ; } } return sum ; } int main ( ) { int a [ ] = { 10 , 10 , 10 , 10 , 11 , 10 , 11 , 10 , 9 , 9 , 8 , 8 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << MaxTotalRectangleArea ( a , n ) ; return 0 ; }