Maximum area of a piece of cake after horizontal and vertical cuts
November 15, 2022
greedyProblem URL: Maximum area of a piece of cake after horizontal and vertical cuts
We will add border cuts to our horizontal and vertical cuts. Then all we need to do is consider all horizontal gaps between adjacent cuts, all vertical gaps between adjacent cuts, choose the biggest among each group and multiply them. Why it will work? Imagine, that we have horizontal gaps say 1, 7, 3 and vertical gaps 8, 3, 9, then maximum among products of numbers max(18, 13, 19, 78, 73, 79, 38, 33, 39) = 79.
class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
MOD = 10**9+7
height = sorted([0]+horizontalCuts+[h])
weight = sorted([0]+verticalCuts+[w])
return max(j-i for i,j in zip(height, height[1:])) * max(j-i for i,j in zip(weight, weight[1:])) % MOD
Time complexity: O(nlogn+mlogm)
Space complexity: O(n+m)