最大化网格图中正方形空洞的面积
难度:
标签:
题目描述
You are given the two integers, n
and m
and two integer arrays, hBars
and vBars
. The grid has n + 2
horizontal and m + 2
vertical bars, creating 1 x 1 unit cells. The bars are indexed starting from 1
.
You can remove some of the bars in hBars
from horizontal bars and some of the bars in vBars
from vertical bars. Note that other bars are fixed and cannot be removed.
Return an integer denoting the maximum area of a square-shaped hole in the grid, after removing some bars (possibly none).
Example 1:
Input: n = 2, m = 1, hBars = [2,3], vBars = [2]
Output: 4
Explanation:
The left image shows the initial grid formed by the bars. The horizontal bars are [1,2,3,4]
, and the vertical bars are [1,2,3]
.
One way to get the maximum square-shaped hole is by removing horizontal bar 2 and vertical bar 2.
Example 2:
Input: n = 1, m = 1, hBars = [2], vBars = [2]
Output: 4
Explanation:
To get the maximum square-shaped hole, we remove horizontal bar 2 and vertical bar 2.
Example 3:
Input: n = 2, m = 3, hBars = [2,3], vBars = [2,4]
Output: 4
Explanation:
One way to get the maximum square-shaped hole is by removing horizontal bar 3, and vertical bar 4.
Constraints:
1 <= n <= 109
1 <= m <= 109
1 <= hBars.length <= 100
2 <= hBars[i] <= n + 1
1 <= vBars.length <= 100
2 <= vBars[i] <= m + 1
- All values in
hBars
are distinct. - All values in
vBars
are distinct.
代码结果
运行时间: 24 ms, 内存: 16.7 MB
/*
* 思路:
* 1. 找出横线段和竖线段中连续的最大间隔。
* 2. 横线段和竖线段的最大间隔决定了最大正方形的边长。
* 3. 最大正方形的面积即为最大间隔的平方。
*/
import java.util.Arrays;
import java.util.stream.IntStream;
public class MaxSquareAreaStream {
public static int maxSquareArea(int n, int m, int[] hBars, int[] vBars) {
Arrays.sort(hBars);
Arrays.sort(vBars);
int maxHGap = IntStream.range(0, hBars.length - 1)
.map(i -> hBars[i + 1] - hBars[i] - 1)
.reduce(Math.max(hBars[0] - 1, n + 2 - hBars[hBars.length - 1]), Math::max);
int maxVGap = IntStream.range(0, vBars.length - 1)
.map(i -> vBars[i + 1] - vBars[i] - 1)
.reduce(Math.max(vBars[0] - 1, m + 2 - vBars[vBars.length - 1]), Math::max);
int maxSquareSide = Math.min(maxHGap, maxVGap);
return maxSquareSide * maxSquareSide;
}
public static void main(String[] args) {
int n = 2, m = 1;
int[] hBars = {2, 3};
int[] vBars = {2};
System.out.println(maxSquareArea(n, m, hBars, vBars)); // 输出 4
}
}
解释
方法:
时间复杂度:
空间复杂度: