Find the Largest Area of Square Inside Two Rectangles(Intersection)

136 Views Asked by At

There exist n rectangles in a 2D plane. We have 2D integer arrays bottomLeft and topRight, both of size n x 2, representing the bottom-left and top-right coordinates of the ith rectangle respectively. We can select a region formed from the intersection of two of the given rectangles such that it is largest (0 if no intersection). This is my solution to it, i am getting a few test cases passed but getting stuck in Others

class Solution {
    public long largestSquareArea(int[][] bottomLeft, int[][] topRight) {
        int n = bottomLeft.length;
        int maxArea = 0;

        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int[] intersection = intersect(
                        new int[]{bottomLeft[i][0], bottomLeft[i][1], topRight[i][0], topRight[i][1]},
                        new int[]{bottomLeft[j][0], bottomLeft[j][1], topRight[j][0], topRight[j][1]});
                if (intersection != null) {
                    int sideLength = Math.min(intersection[2] - intersection[0], intersection[3] - intersection[1]);
                    maxArea = Math.max(maxArea, sideLength * sideLength);
                }
            }
        }

        return maxArea;
    }

    private int[] intersect(int[] rect1, int[] rect2) {
        int x1 = Math.max(rect1[0], rect2[0]);
        int y1 = Math.max(rect1[1], rect2[1]);
        int x2 = Math.min(rect1[2], rect2[2]);
        int y2 = Math.min(rect1[3], rect2[3]);
        if (x1 < x2 && y1 < y2) {
            return new int[]{x1, y1, x2, y2};
        }
        return null;
    }
}

0

There are 0 best solutions below