Open In App

Maximum area rectangle by picking four sides from array

Last Updated : 19 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of n positive integers that represent lengths. Find out the maximum possible area whose four sides are picked from the given array. Note that a rectangle can only be formed if there are two pairs of equal values in the 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 the array. If there are more than two pairs, then pick the two pairs with maximum values. A simple solution is to do the following. 

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

Implementation:

C++




// CPP program for finding maximum area possible
// of a rectangle
#include <bits/stdc++.h>
using namespace std;
  
// function for finding max area
int 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 function
int 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




// Java program for finding maximum area 
// possible of a rectangle
import 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




# Python3 program for finding 
# maximum area possible of 
# a rectangle
  
# function for finding
# max area
def 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 code
arr = [4, 2, 1, 4, 6, 6, 2, 5]
n = len(arr)
print(findArea(arr, n))
  
# This code is contributed 
# by Smitha


C#




// C# program for finding maximum area 
// possible of a rectangle 
using System;
using System.Collections;
  
class GFG 
// function for finding max area 
static 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 Code
public 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
// PHP program for finding maximum area possible
// of a rectangle
  
// function for finding max area
function 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.
?>


Javascript




<script>
  
// Javascript program for finding maximum area possible
// of a rectangle
  
// function for finding max area
function 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 function
var 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) as one traversal of array takes O(n) time and sorting the array takes n logn extra time , hence overall time taken by the algorithm is O(n Log n)
Auxiliary Space: O(1) since no extra array is used so it takes constant space

Method 2 (Hashing): The idea is to insert all first occurrences of elements in a hash set. For second occurrences, keep track of the maximum of two values. 

Below is the implementation of the above approach:

C++




// CPP program for finding maximum area possible
// of a rectangle
#include <bits/stdc++.h>
using namespace std;
  
// function for finding max area
int 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 function
int 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




// Java program for finding maximum 
// area possible of a rectangle
import 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


Python3





C#





Javascript





Output

24

Time Complexity: O(n) as only one traversal of array is required to complete all operations hence overall complexity turns out be O(n)
Auxiliary Space: O(n) since an unordered set is used, in worst case all elements will be inserted into the set thus occupying O(n) space.

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads