Largest area square in an array when elements can be shuffled | Java implementation of the approach ; Function that returns true if it is possible to make a square with side equal to l ; To store the count of elements greater than or equal to l ; Increment the count ; If the count becomes greater than or equal to l ; Function to return the maximum area of the square that can be obtained ; If square is possible with side length m ; Try to find a square with smaller side length ; Return the area ; Driver code
class GFG { static boolean isSquarePossible ( int arr [ ] , int n , int l ) { int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] >= l ) cnt ++ ; if ( cnt >= l ) return true ; } return false ; } static int maxArea ( int arr [ ] , int n ) { int l = 0 , r = n ; int len = 0 ; while ( l <= r ) { int m = l + ( ( r - l ) / 2 ) ; if ( isSquarePossible ( arr , n , m ) ) { len = m ; l = m + 1 ; } else r = m - 1 ; } return ( len * len ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 4 , 5 , 5 } ; int n = arr . length ; System . out . println ( maxArea ( arr , n ) ) ; } }