LC 3047 - Find the Largest Area of Square Inside Two Rectangles
Approach We check all pairs of the square and find its intersection, this can be done easily by maintaingin the minimum for top and right, and maximum for bottom and left, and then we can somply compare the width for that intersection area. Code class Solution { public: long long largestSquareArea(vector<vector<int>>& bottomLeft, vector<vector<int>>& topRight) { int n = bottomLeft.size(); int maxWidth = 0; for(int i = 0 ; i < n ; ++i) { for(int j = i+1 ; j < n ; ++j) { int left = max(bottomLeft[i][0], bottomLeft[j][0]); int right = min(topRight[i][0], topRight[j][0]); if(right <= left) continue; int bottom = max(bottomLeft[i][1], bottomLeft[j][1]); int top = min(topRight[i][1], topRight[j][1]); if(top <= bottom) continue; maxWidth = max(maxWidth, min(right-left, top-bottom)); } } return (long long)maxWidth * maxWidth; } };