题目是LeetCode第191场周赛的第二题,链接:1465. 切割后面积最大的蛋糕。具体描述见原题。
题目其实还是蛮简单的,面积最大就意味着在长和宽方向上的边都是最大的,这样得到的面积才是最大的,所以我们就只需要找到长和宽方向上的最大边就行了。所以首先对两个代表了切割位置的数组进行排序,然后分别遍历,求出所有的边长(num[i]-num[i-1]就是了),然后将两个最大边长乘起来就得到了答案。时间复杂度为
O
(
m
l
o
g
m
+
n
l
o
g
n
)
O(mlogm+nlogn)
O(mlogm+nlogn),空间复杂度为
O
(
1
)
O(1)
O(1)。
JAVA版代码如下:
class Solution {
public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) {
Arrays.sort(horizontalCuts);
Arrays.sort(verticalCuts);
int hMax = 0, wMax = 0;
int prev = 0;
for (int hc : horizontalCuts) {
hMax = Math.max(hc - prev, hMax);
prev = hc;
}
hMax = Math.max(h - prev, hMax);
prev = 0;
for (int vc : verticalCuts) {
wMax = Math.max(vc - prev, wMax);
prev = vc;
}
wMax = Math.max(w - prev, wMax);
return (int)((hMax * 1l * wMax) % 1000_000_007);
}
}
提交结果如下:
Python版代码如下:
class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
horizontalCuts.sort()
verticalCuts.sort()
horizontalCuts.append(h)
verticalCuts.append(w)
hMax = 0
prev = 0
for hc in horizontalCuts:
hMax = max(hMax, hc - prev)
prev = hc
vMax = 0
prev = 0
for vc in verticalCuts:
vMax = max(vMax, vc - prev)
prev = vc
return (hMax * vMax) % 1000_000_007
提交结果如下:
931

被折叠的 条评论
为什么被折叠?



