Maximum area rectangle by picking four sides from array

16 Mar, 2022
Given an array of n positive integers that represent lengths. Find out the maximum possible area whose four sides are picked from given array. Note that a rectangle can only be formed if there are two pairs of equal values in given array.
Examples: 
Input : arr[] = {2, 1, 2, 5, 4, 4}
Output : 8
Explanation : Dimension will be 4 * 2

Input : arr[] = {2, 1, 3, 5, 4, 4}
Output : 0
Explanation : No rectangle possible
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. 1) Sort the given array. 2) Traverse array from largest to smallest value and return two pairs with maximum values.
C++
Java
Python3
C#
PHP
Javascript
// CPP program for finding maximum area possible// of a rectangle#include <bits/stdc++.h>using namespace std; // function for finding max areaint findArea(int arr[], int n){    // sort array in non-increasing order    sort(arr, arr + n, greater<int>());     // Initialize two sides of rectangle    int dimension[2] = { 0, 0 };     // traverse through array    for (int i = 0, j = 0; i < n - 1 && j < 2; i++)         // if any element occurs twice        // store that as dimension        if (arr[i] == arr[i + 1])            dimension[j++] = arr[i++];     // return the product of dimensions    return (dimension[0] * dimension[1]);} // driver functionint main(){    int arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 };    int n = sizeof(arr) / sizeof(arr[0]);    cout << findArea(arr, n);    return 0;}
// Java program for finding maximum area// possible of a rectangleimport java.util.Arrays;import java.util.Collections; public class GFG{        // function for finding max area    static int findArea(Integer arr[], int n)    {        // sort array in non-increasing order        Arrays.sort(arr, Collections.reverseOrder());              // Initialize two sides of rectangle        int[] dimension = { 0, 0 };              // traverse through array        for (int i = 0, j = 0; i < n - 1 && j < 2;                                           i++)                  // if any element occurs twice            // store that as dimension            if (arr[i] == arr[i + 1])                dimension[j++] = arr[i++];              // return the product of dimensions        return (dimension[0] * dimension[1]);    }          // driver function    public static void main(String args[])    {        Integer arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 };        int n = arr.length;        System.out.println(findArea(arr, n));    }}// This code is contributed by Sumit Ghosh
# Python3 program for finding# maximum area possible of# a rectangle # function for finding# max areadef findArea(arr, n):     # sort array in    # non-increasing order    arr.sort(reverse = True)     # Initialize two    # sides of rectangle    dimension = [0, 0]     # traverse through array    i = 0    j = 0    while(i < n - 1 and j < 2):         # if any element occurs twice        # store that as dimension        if (arr[i] == arr[i + 1]):            dimension[j] = arr[i]            j += 1            i += 1        i += 1             # return the product    # of dimensions    return (dimension[0] *            dimension[1]) # Driver codearr = [4, 2, 1, 4, 6, 6, 2, 5]n = len(arr)print(findArea(arr, n)) # This code is contributed# by Smitha
// C# program for finding maximum area// possible of a rectangleusing System;using System.Collections; class GFG{// function for finding max areastatic int findArea(int []arr, int n){    // sort array in non-increasing order    Array.Sort(arr);    Array.Reverse(arr);     // Initialize two sides of rectangle    int[] dimension = { 0, 0 };     // traverse through array    for (int i = 0, j = 0;             i < n - 1 && j < 2; i++)         // if any element occurs twice        // store that as dimension        if (arr[i] == arr[i + 1])            dimension[j++] = arr[i++];     // return the product of dimensions    return (dimension[0] * dimension[1]);} // Driver Codepublic static void Main(String []args){    int []arr = { 4, 2, 1, 4, 6, 6, 2, 5 };    int n = arr.Length;    Console.Write(findArea(arr, n));}} // This code is contributed// by PrinciRaj1992
<?php// PHP program for finding maximum area possible// of a rectangle // function for finding max areafunction findArea($arr, $n){         // sort array in non-    // increasing order    rsort($arr);     // Initialize two sides    // of rectangle    $dimension = array( 0, 0 );     // traverse through array    for( $i = 0, $j = 0; $i < $n - 1 &&                           $j < 2; $i++)         // if any element occurs twice        // store that as dimension        if ($arr[$i] == $arr[$i + 1])            $dimension[$j++] = $arr[$i++];     // return the product    // of dimensions    return ($dimension[0] *            $dimension[1]);}     // Driver Code    $arr = array(4, 2, 1, 4, 6, 6, 2, 5);    $n =count($arr);    echo findArea($arr, $n);     // This code is contributed by anuj_67.?>
<script> // Javascript program for finding maximum area possible// of a rectangle // function for finding max areafunction findArea(arr, n){    // sort array in non-increasing order    arr.sort((a,b)=>{return b-a;})     // Initialize two sides of rectangle    var dimension = [0,0];     // traverse through array    for (var i = 0, j = 0; i < n - 1 && j < 2; i++)         // if any element occurs twice        // store that as dimension        if (arr[i] == arr[i + 1])            dimension[j++] = arr[i++];     // return the product of dimensions    return (dimension[0] * dimension[1]);} // driver functionvar arr = [ 4, 2, 1, 4, 6, 6, 2, 5 ];var n = arr.length;document.write( findArea(arr, n)); </script>
Output: 
24
Time Complexity : O(n Log n) Method 2 (Hashing) The idea is to insert all first occurrences of elements in a hash set. For second occurrences, keep track of maximum two values. 
C++
Java
Python3
C#
Javascript
// CPP program for finding maximum area possible// of a rectangle#include <bits/stdc++.h>using namespace std; // function for finding max areaint findArea(int arr[], int n){    unordered_set<int> s;     // traverse through array    int first = 0, second = 0;    for (int i = 0; i < n; i++) {         // If this is first occurrence of arr[i],        // simply insert and continue        if (s.find(arr[i]) == s.end()) {            s.insert(arr[i]);            continue;        }         // If this is second (or more) occurrence,        // update first and second maximum values.        if (arr[i] > first) {            second = first;            first = arr[i];        } else if (arr[i] > second)            second = arr[i];    }     // return the product of dimensions    return (first * second);} // driver functionint main(){    int arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 };    int n = sizeof(arr) / sizeof(arr[0]);    cout << findArea(arr, n);    return 0;}
// Java program for finding maximum// area possible of a rectangleimport java.util.HashSet;import java.util.Set; public class GFG{        // function for finding max area    static int findArea(int arr[], int n)    {        //unordered_set<int> s;                 Set<Integer> s = new HashSet<>();              // traverse through array        int first = 0, second = 0;        for (int i = 0; i < n; i++) {                  // If this is first occurrence of            // arr[i], simply insert and continue            if (!s.contains(arr[i])) {                s.add(arr[i]);                continue;            }                  // If this is second (or more)            // occurrence, update first and            // second maximum values.            if (arr[i] > first) {                second = first;                first = arr[i];            } else if (arr[i] > second)                second = arr[i];        }              // return the product of dimensions        return (first * second);    }          // driver function    public static void main(String args[])    {        int arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 };        int n = arr.length;        System.out.println(findArea(arr, n));    }}// This code is contributed by Sumit Ghosh
# Python 3 program for finding maximum# area possible of a rectangle # function for finding max areadef findArea(arr, n):     s = []     # traverse through array    first = 0    second = 0    for i in range(n) :         # If this is first occurrence of        # arr[i], simply insert and continue        if arr[i] not in s:            s.append(arr[i])            continue         # If this is second (or more) occurrence,        # update first and second maximum values.        if (arr[i] > first) :            second = first            first = arr[i]        else if (arr[i] > second):            second = arr[i]     # return the product of dimensions    return (first * second) # Driver Codeif __name__ == "__main__":         arr = [ 4, 2, 1, 4, 6, 6, 2, 5 ]    n = len(arr)    print(findArea(arr, n)) # This code is contributed by ita_c
using System;using System.Collections.Generic; // c# program for finding maximum // area possible of a rectangle public class GFG{    // function for finding max area    public static int findArea(int[] arr, int n)    {        //unordered_set<int> s;         ISet<int> s = new HashSet<int>();         // traverse through array        int first = 0, second = 0;        for (int i = 0; i < n; i++)        {             // If this is first occurrence of             // arr[i], simply insert and continue            if (!s.Contains(arr[i]))            {                s.Add(arr[i]);                continue;            }             // If this is second (or more)             // occurrence, update first and             // second maximum values.            if (arr[i] > first)            {                second = first;                first = arr[i];            }            else if (arr[i] > second)            {                second = arr[i];            }        }         // return the product of dimensions        return (first * second);    }     // driver function    public static void Main(string[] args)    {        int[] arr = new int[] {4, 2, 1, 4, 6, 6, 2, 5};        int n = arr.Length;        Console.WriteLine(findArea(arr, n));    }} // This code is contributed by Shrikant13
<script> // Javascript program for finding maximum// area possible of a rectangle     // Function for finding max areafunction findArea(arr, n){    let s = new Set();       // Traverse through array    let first = 0, second = 0;    for(let i = 0; i < n; i++)    {                 // If this is first occurrence of        // arr[i], simply insert and continue        if (!s.has(arr[i]))        {            s.add(arr[i]);            continue;        }           // If this is second (or more)        // occurrence, update first and        // second maximum values.        if (arr[i] > first)        {            second = first;            first = arr[i];        }        else if (arr[i] > second)            second = arr[i];    }       // Return the product of dimensions    return (first * second);} // Driver Codelet arr = [ 4, 2, 1, 4, 6, 6, 2, 5 ];let n = arr.length; document.write(findArea(arr, n)); // This code is contributed by avanitrachhadiya2155     </script>
Output: 
24
Time Complexity: O(n)
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
vt_m
Smitha Dinesh Semwal
shrikanth13
princiraj1992
ukasp
rutvik_56
avanitrachhadiya2155
simmytarika5
area-volume-programs
Arrays
Hash
Sorting
Arrays
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum