Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts

Given a rectangular cake of height h and width w, and two integer arrays horizontalCuts and verticalCuts where horizontalCuts[i] is the distance from the top of the cake to the i-th horizontal cut and verticalCuts[j] is the distance from the left side of the cake to the j-th veritcal cut, return the maximum area of a peice of cake after you cut it at the given horizontal and vertical positions. Since the answer may be a large number, return it modulo 10^9 + 7.

Example 1:

img

Input: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3] Output: 4 Explanation: The red lines are the horizontal and vertical cuts. The green piece of cake has the maximum area.

Example 2:

img

Input: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1] Output: 6 Explanation: The red lines are the horizontal and vertical cuts. The green and yellow pieces have the maximum area.

Example 3:

Input: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3] Output: 9

Constraints:

  • 2 <= h, w <= 10^9
  • 1 <= horizontalCuts.length < min(h, 10^5)
  • 1 <= verticalCuts.length < min(w, 10^5)
  • 1 <= horizontalCuts[i] < h
  • 1 <= verticalCuts[i] < w
  • All elements in horizontalCuts are distinct.
  • All elements in verticalCuts are disitnct.

Solution:

var maxArea = function(h, w, horizontalCuts, verticalCuts) {
    const MOD = 10**9 + 7;
    
    // Sort the cuts and include boundaries
    horizontalCuts.sort((a, b) => a - b);
    horizontalCuts.unshift(0);
    horizontalCuts.push(h);
    
    verticalCuts.sort((a, b) => a - b);
    verticalCuts.unshift(0);
    verticalCuts.push(w);
    
    let maxHorizGap = 0;
    for (let i = 1; i < horizontalCuts.length; i++) {
        const gap = horizontalCuts[i] - horizontalCuts[i-1];
        if (gap > maxHorizGap) {
            maxHorizGap = gap;
        }
    }
    
    let maxVertGap = 0;
    for (let j = 1; j < verticalCuts.length; j++) {
        const gap = verticalCuts[j] - verticalCuts[j-1];
        if (gap > maxVertGap) {
            maxVertGap = gap;
        }
    }
    
    return (BigInt(maxHorizGap) * BigInt(maxVertGap)) % BigInt(MOD);
};

Note: When h and w are up to 1e9, the product may exceed Number.MAX_SAFE_INTEGER. Use BigInt or modulo arithmetic carefully.

Tags: LeetCode algorithm Sorting greedy

Posted on Sun, 11 Oct 2026 16:56:14 +0000 by froggie81