Input: points =[[1,1],[1,3],[3,1],[3,3]]Output: 4Explanation:
****
We can make a rectangle with these 4 points as corners and there is no other
point that lies inside or on the border. Hence, the maximum possible area
would be 4.
Input: points =[[1,1],[1,3],[3,1],[3,3],[2,2]]Output:****-1Explanation:
****
There is only one rectangle possible iswith points `[1,1], [1,3], [3,1]` and
`[3,3]` but `[2,2]` will always lie inside it. Hence, returning -1.
Input: points =[[1,1],[1,3],[3,1],[3,3],[1,2],[3,2]]Output: 2Explanation:
****
The maximum area rectangle is formed by the points `[1,3], [1,2], [3,2],
[3,3]`, which has an area of 2. Additionally, the points `[1,1], [1,2], [3,1],
[3,2]` also form a valid rectangle with the same area.
To form a rectangle with axis-aligned edges, we need two pairs of points with the same x and two with the same y. For each pair of points that could be opposite corners, check if the other two corners exist. To ensure no other point is inside or on the border, check all points are strictly outside the rectangle.
classSolution {
funmaxAreaRect(points: Array<IntArray>): Int {
val s = mutableSetOf<Pair<Int,Int>>()
for (p in points) s.add(Pair(p[0], p[1]))
var ans = -1val n = points.size
for (i in0 until n) {
for (j in i+1 until n) {
val(x1, y1) = points[i]
val(x2, y2) = points[j]
if (x1 == x2 || y1 == y2) continueif (Pair(x1, y2) in s && Pair(x2, y1) in s) {
val minx = minOf(x1, x2)
val maxx = maxOf(x1, x2)
val miny = minOf(y1, y2)
val maxy = maxOf(y1, y2)
var valid = truefor (p in points) {
if (p[0] > minx && p[0] < maxx && p[1] > miny && p[1] < maxy) {
valid = falsebreak }
}
if (valid) ans = maxOf(ans, kotlin.math.abs(x1-x2)*kotlin.math.abs(y1-y2))
}
}
}
return ans
}
}
classSolution:
defmaxAreaRect(self, points: list[list[int]]) -> int:
s = set(map(tuple, points))
ans =-1 n = len(points)
for i in range(n):
for j in range(i+1, n):
x1, y1 = points[i]
x2, y2 = points[j]
if x1 == x2 or y1 == y2:
continueif (x1, y2) in s and (x2, y1) in s:
minx, maxx = min(x1, x2), max(x1, x2)
miny, maxy = min(y1, y2), max(y1, y2)
valid =Truefor px, py in points:
if minx < px < maxx and miny < py < maxy:
valid =Falsebreakif valid:
ans = max(ans, abs(x1-x2)*abs(y1-y2))
return ans