Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts Problem
Description
LeetCode Problem 1465.
You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where:
horizontalCuts[i]is the distance from the top of the rectangular cake to thei^thhorizontal cut and similarly, andverticalCuts[j]is the distance from the left of the rectangular cake to thej^thvertical cut.
Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts. Since the answer can be a large number, return this modulo 10^9 + 7.
Example 1:

Input: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]
Output: 4
Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.
Example 2:

Input: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]
Output: 6
Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.
Example 3:
Input: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]
Output: 9
Constraints:
2 <= h, w <= 10^91 <= horizontalCuts.length <= min(h - 1, 10^5)1 <= verticalCuts.length <= min(w - 1, 10^5)1 <= horizontalCuts[i] < h1 <= verticalCuts[i] < w- All the elements in
horizontalCutsare distinct. - All the elements in
verticalCutsare distinct.
Solution
Approach: Widest Gap in Each Direction
Every piece is the intersection of one horizontal strip and one vertical strip, and every combination of a strip from each direction is a piece. So the biggest piece is simply the tallest horizontal strip times the widest vertical strip, and the two directions can be handled on their own.
To find the tallest strip, sort horizontalCuts and take the largest difference between neighbouring cuts. Do not forget the two edges of the cake: the strip from the top (0) to the first cut, and the strip from the last cut to h. The same goes for the vertical cuts and w.
Both gaps can be close to 109, so their product does not fit in 32 bits: multiply in 64-bit integers (in JavaScript, with BigInt, since a double cannot hold the exact product) and only then take the result modulo 109 + 7.
Complexity: O(a log a + b log b) time to sort a horizontal and b vertical cuts, and O(1) extra space beyond the sort.
class Solution:
def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
def widest_gap(cuts: List[int], size: int) -> int:
cuts = sorted(cuts)
gap = max(cuts[0], size - cuts[-1]) # the pieces at the two edges
for i in range(1, len(cuts)):
gap = max(gap, cuts[i] - cuts[i - 1])
return gap
return widest_gap(horizontalCuts, h) * widest_gap(verticalCuts, w) % (10**9 + 7)