Area of the largest square that can be formed from the given length sticks using Hashing

Given an array arr[] of N integers representing the heights of the sticks. The task is to find the area of the largest square that can be formed using these sticks and the count of such squares. Note that a single side of the square can only use a single stick.
Examples:Â
Input: arr[] = {5, 3, 2, 3, 6, 3, 3}Â
Output:Â
Area = 9Â
Count = 1Â
Side of the square will be 3 andÂ
only one such square is possible.
Input: arr[] = {2, 2, 2, 9, 2, 2, 2, 2, 2}Â
Output:Â
Area = 4Â
Count = 2Â
Approach: Count the frequencies of all the elements of the array. Now, starting from the maximum (in order to maximize the area) find the first frequency which is at least 4 so that a square can be formed then the area can be calculated as freq[i] * freq[i] and the count of such squares will be freq[i] / 4.
Below is the implementation of the above approach:Â
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;Â
// Function to find the area of the largest// square that can be formed// and the count of such squaresvoid findMaxSquare(int arr[], int n){Â
    // Maximum value from the array    int maxVal = *max_element(arr, arr + n);Â
    // Update the frequencies of    // the array elements    int freq[maxVal + 1] = { 0 };    for (int i = 0; i < n; i++)        freq[arr[i]]++;Â
    // Starting from the maximum length sticks    // in order to maximize the area    for (int i = maxVal; i > 0; i--) {Â
        // The count of sticks with the current        // length has to be at least 4        // in order to form a square        if (freq[i] >= 4) {            cout << "Area = " << (pow(i, 2));            cout << "\nCount = " << (freq[i] / 4);            return;        }    }Â
    // Impossible to form a square    cout << "-1";}Â
// Driver codeint main(){Â Â Â Â int arr[] = { 2, 2, 2, 9, 2, 2, 2, 2, 2 };Â Â Â Â int n = sizeof(arr) / sizeof(arr[0]);Â
    findMaxSquare(arr, n);Â
    return 0;} |
Java
// Java implementation of the approachimport java.util.*;Â
class GFG {Â
// Function to find the area of the largest// square that can be formed// and the count of such squaresstatic void findMaxSquare(int arr[], int n){Â
    // Maximum value from the array    int maxVal = Arrays.stream(arr).max().getAsInt();Â
    // Update the frequencies of    // the array elements    int []freq = new int[maxVal + 1];    for (int i = 0; i < n; i++)        freq[arr[i]]++;Â
    // Starting from the maximum length sticks    // in order to maximize the area    for (int i = maxVal; i > 0; i--)    {Â
        // The count of sticks with the current        // length has to be at least 4        // in order to form a square        if (freq[i] >= 4)         {            System.out.print("Area = " +                             (Math.pow(i, 2)));            System.out.print("\nCount = " +                             (freq[i] / 4));            return;        }    }Â
    // Impossible to form a square    System.out.print("-1");}Â
// Driver codepublic static void main(String[] args){Â Â Â Â int arr[] = { 2, 2, 2, 9, 2, 2, 2, 2, 2 };Â Â Â Â int n = arr.length;Â
    findMaxSquare(arr, n);}} Â
// This code is contributed by Princi Singh |
Python3
# Python3 implementation of the approach Â
# Function to find the area of the largest # square that can be formed # and the count of such squares def findMaxSquare(arr, n) : Â
    # Maximum value from the array     maxVal = max(arr); Â
    # Update the frequencies of     # the array elements     freq = [0] * (maxVal + 1) ;     for i in range(n) :        freq[arr[i]] += 1; Â
    # Starting from the maximum length sticks     # in order to maximize the area     for i in range(maxVal, 0, -1) :Â
        # The count of sticks with the current         # length has to be at least 4         # in order to form a square         if (freq[i] >= 4) :            print("Area = ", pow(i, 2));             print("Count =", freq[i] // 4);             return; Â
    # Impossible to form a square     print("-1"); Â
# Driver code if __name__ == "__main__" : Â
    arr = [ 2, 2, 2, 9, 2, 2, 2, 2, 2 ];     n = len(arr); Â
    findMaxSquare(arr, n); Â
# This code is contributed by AnkitRai01 |
C#
// C# implementation of the approachusing System;using System.Linq; Â
class GFG {Â
// Function to find the area of the largest// square that can be formed// and the count of such squaresstatic void findMaxSquare(int []arr, int n){Â
    // Maximum value from the array    int maxVal = arr.Max();Â
    // Update the frequencies of    // the array elements    int []freq = new int[maxVal + 1];    for (int i = 0; i < n; i++)        freq[arr[i]]++;Â
    // Starting from the maximum length sticks    // in order to maximize the area    for (int i = maxVal; i > 0; i--)    {Â
        // The count of sticks with the current        // length has to be at least 4        // in order to form a square        if (freq[i] >= 4)         {            Console.Write("Area = " +                          (Math.Pow(i, 2)));            Console.Write("\nCount = " +                          (freq[i] / 4));            return;        }    }Â
    // Impossible to form a square    Console.Write("-1");}Â
// Driver codepublic static void Main(String[] args){Â Â Â Â int []arr = { 2, 2, 2, 9, 2, 2, 2, 2, 2 };Â Â Â Â int n = arr.Length;Â
    findMaxSquare(arr, n);}}Â
// This code is contributed by 29AjayKumar |
Javascript
<script>Â
// Javascript implementation of the approachÂ
// Function to find the area of the largest// square that can be formed// and the count of such squaresfunction findMaxSquare(arr, n){Â
    // Maximum value from the array    var maxVal = Math.max(...arr);Â
    // Update the frequencies of    // the array elements    var freq = Array(maxVal + 1).fill(0);    for (var i = 0; i < n; i++)        freq[arr[i]]++;Â
    // Starting from the maximum length sticks    // in order to maximize the area    for (var i = maxVal; i > 0; i--) {Â
        // The count of sticks with the current        // length has to be at least 4        // in order to form a square        if (freq[i] >= 4) {            document.write("Area = " + (Math.pow(i, 2)));            document.write("<br>Count = " + (freq[i] / 4));            return;        }    }Â
    // Impossible to form a square    document.write("-1");}Â
// Driver codevar arr = [ 2, 2, 2, 9, 2, 2, 2, 2, 2 ];var n = arr.length;findMaxSquare(arr, n);Â
</script> |
Area = 4 Count = 2
Â
Time Complexity: O(n)
Auxiliary Space: O(n)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



