Maximize count of unique Squares that can be formed with N arbitrary points in coordinate plane
Given a positive integer N, the task is to find the maximum number of unique squares that can be formed with N arbitrary points in the coordinate plane.
Note: Any two squares that are not overlapping are considered unique.
Input: N = 9
Consider the below square consisting of N points:
The squares ABEF, BCFE, DEHG, EFIH is one of the possible squares of size 1 which are non-overlapping with each other.
The square ACIG is also one of the possible squares of size 2.
Input: N = 6
Approach: This problem can be solved based on the following observations:
- Observe that if N is a perfect square then the maximum number of squares will be formed when sqrt(N)*sqrt(N) points form a grid of sqrt(N)*sqrt(N) and all of them are equally spaces.
- But when N is not a perfect square, then it still forms a grid but with the greatest number which is a perfect square having a value less than N.
- The remaining coordinates can be placed around the edges of the grid which will lead to maximum possible squares.
Follow the below steps to solve the problem:
- Initialize a variable, say ans that stores the resultant count of squares formed.
- Find the maximum possible grid size as sqrt(N) and the count of all possible squares formed up to length len to the variable ans which can be calculated by .
- Decrement the value of N by len*len.
- If the value of N is at least len, then all other squares can be formed by placing them in another cluster of points. Find the count of squares as calculated in Step 2 for the value of len.
- After completing the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
Time Complexity: O(sqrt(N))
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.