You are given an array rectangles where rectangles[i] = [li, wi]
represents the ith rectangle of length li and width wi.
You can cut the ith rectangle to form a square with a side length of k if both k <= li and k <= wi. For example, if you have a rectangle [4,6], you can cut it to get a square with a side length of at most 4.
Let maxLen be the side length of the largest square you can obtain from any of the given rectangles.
Return _thenumber of rectangles that can make a square with a side length of _maxLen.
Input: rectangles =[[5,8],[3,9],[5,12],[16,5]]Output: 3Explanation: The largest squares you can get from each rectangle are of lengths [5,3,5,5].The largest possible square is of length 5, and you can get it out of 3 rectangles.
For each rectangle, the largest square you can cut has side length equal to the minimum of its two sides. We find the maximum such value among all rectangles, then count how many rectangles can form a square of that size.
classSolution {
public:int countGoodRectangles(vector<vector<int>>& rectangles) {
int maxLen =0, ans =0;
for (auto& r : rectangles) {
int side = min(r[0], r[1]);
if (side > maxLen) { maxLen = side; ans =1; }
elseif (side == maxLen) ++ans;
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
funccountGoodRectangles(rectangles [][]int) int {
maxLen, ans:=0, 0for_, r:=rangerectangles {
side:=r[0]
ifr[1] < side { side = r[1] }
ifside > maxLen {
maxLen, ans = side, 1 } elseifside==maxLen {
ans++ }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
publicintcountGoodRectangles(int[][] rectangles) {
int maxLen = 0, ans = 0;
for (int[] r : rectangles) {
int side = Math.min(r[0], r[1]);
if (side > maxLen) {
maxLen = side; ans = 1;
} elseif (side == maxLen) {
ans++;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funcountGoodRectangles(rectangles: Array<IntArray>): Int {
var maxLen = 0var ans = 0for (r in rectangles) {
val side = minOf(r[0], r[1])
if (side > maxLen) {
maxLen = side; ans = 1 } elseif (side == maxLen) {
ans++ }
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defcountGoodRectangles(self, rectangles: list[list[int]]) -> int:
maxLen =0 ans =0for l, w in rectangles:
side = min(l, w)
if side > maxLen:
maxLen = side
ans =1elif side == maxLen:
ans +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfncount_good_rectangles(rectangles: Vec<Vec<i32>>) -> i32 {
letmut max_len =0;
letmut ans =0;
for r in rectangles {
let side = r[0].min(r[1]);
if side > max_len {
max_len = side;
ans =1;
} elseif side == max_len {
ans +=1;
}
}
ans
}
}