Program to find number of rectangles that can form the largest square in Python


Suppose we have an array called rect where rect[i] has two elements [len_i, wid_i], where len_i and wid_i are representing the length and width of ith rectangle respectively. Now we can cut the ith rectangle to form a square whose side length is of k if both k <= lenn_i and k <= wid_i. So for example, if we have a rectangle [4,6], then we can cut it to get a square with a side length of at most 4. Now consider a parameter called maxLen be the side length of the largest square we can get from any of the given rectangles. We have to find the number of rectangles that we can make a square with a side length of maxLen.

So, if the input is like rect = [[6,9],[4,10],[6,13],[17,6]], then the output will be 3 as we can get largest squares of sides [6, 4, 6, 6], so there are three rectangles which are largest.

To solve this, we will follow these steps −

  • m := a new list

  • for each r in rect, do

    • insert minimum of r at the end of m

  • count (maximum of m) present in m and return

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

def solve(rect):
   m = []
   for r in rect:
      m.append(min(r))

   return m.count(max(m))

rect = [[6,9],[4,10],[6,13],[17,6]]
print(solve(rect))

Input

[[6,9],[4,10],[6,13],[17,6]]

Output

3

Updated on: 18-May-2021

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements