移除栅栏得到的正方形田地的最大面积
难度:
标签:
题目描述
There is a large (m - 1) x (n - 1)
rectangular field with corners at (1, 1)
and (m, n)
containing some horizontal and vertical fences given in arrays hFences
and vFences
respectively.
Horizontal fences are from the coordinates (hFences[i], 1)
to (hFences[i], n)
and vertical fences are from the coordinates (1, vFences[i])
to (m, vFences[i])
.
Return the maximum area of a square field that can be formed by removing some fences (possibly none) or -1
if it is impossible to make a square field.
Since the answer may be large, return it modulo 109 + 7
.
Note: The field is surrounded by two horizontal fences from the coordinates (1, 1)
to (1, n)
and (m, 1)
to (m, n)
and two vertical fences from the coordinates (1, 1)
to (m, 1)
and (1, n)
to (m, n)
. These fences cannot be removed.
Example 1:
Input: m = 4, n = 3, hFences = [2,3], vFences = [2] Output: 4 Explanation: Removing the horizontal fence at 2 and the vertical fence at 2 will give a square field of area 4.
Example 2:
Input: m = 6, n = 7, hFences = [2], vFences = [4] Output: -1 Explanation: It can be proved that there is no way to create a square field by removing fences.
Constraints:
3 <= m, n <= 109
1 <= hFences.length, vFences.length <= 600
1 < hFences[i] < m
1 < vFences[i] < n
hFences
andvFences
are unique.
代码结果
运行时间: 644 ms, 内存: 36.2 MB
// 思路:
// 1. 使用Java Stream对水平和垂直栅栏排序,并找到每一块区域的最大边长。
// 2. 通过计算最大正方形边长来判断结果。
// 3. 返回最大正方形的面积,如果没有则返回-1。
// 注意:取余 10^9 + 7
import java.util.*;
import java.util.stream.*;
public class Solution {
public int maxSquareArea(int m, int n, int[] hFences, int[] vFences) {
Arrays.sort(hFences);
Arrays.sort(vFences);
int maxHGap = Math.max(hFences[0] - 1, m - hFences[hFences.length - 1]);
int maxVGap = Math.max(vFences[0] - 1, n - vFences[vFences.length - 1]);
maxHGap = IntStream.range(1, hFences.length)
.map(i -> hFences[i] - hFences[i - 1] - 1)
.reduce(maxHGap, Math::max);
maxVGap = IntStream.range(1, vFences.length)
.map(i -> vFences[i] - vFences[i - 1] - 1)
.reduce(maxVGap, Math::max);
int maxSide = Math.min(maxHGap, maxVGap);
if (maxSide == 0) return -1;
long area = (long) maxSide * maxSide % (1000000007);
return (int) area;
}
}
解释
方法:
时间复杂度:
空间复杂度: