Maximum area rectangle created by selecting four sides from an array

Given a set of n positive integers representing lengths. Determine the maximum possible area whose four sides are chosen from the given array. It should be noted that a rectangle can only be formed if the given array contains two pairs of equal values.

Examples

Method 1 (Sorting)

The task basically reduces to finding two pairs of equal values in array. If there are more than two pairs, then pick the two pairs with maximum values. A simple solution is to do following.

  • Sort the given array.
  • Traverse array from largest to smallest value and return two pairs with maximum values.

Program in C++

Output

24

Time Complexity : O (n Log n)

Method 2 (Hashing)

In a hash set, all first occurrences of elements are inserted. Keep track of no more than two values for second occurrences.

Program in C++

Output

24

Time Complexity : O (n)






Latest Courses