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

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 the i-th horizontal cut and similarly, and verticalCuts[j] is the distance from the left of the rectangular cake to the j-th vertical 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⁹ + 7.

Input & Output

Example 1 — Basic Case
$ Input: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]
Output: 4
💡 Note: After adding boundaries: horizontal cuts [0,1,2,4,5], vertical cuts [0,1,3,4]. Maximum height gap = 5-2 = 3, maximum width gap = 3-1 = 2. But actually max height gap = 2 (4-2) and max width = 2 (3-1), so area = 4.
Example 2 — Single Cut
$ Input: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [1]
Output: 9
💡 Note: Horizontal gaps: [3-0=3, 5-3=2], max = 3. Vertical gaps: [1-0=1, 4-1=3], max = 3. Area = 3×3 = 9.
Example 3 — No Cuts
$ Input: h = 5, w = 4, horizontalCuts = [], verticalCuts = []
Output: 20
💡 Note: No internal cuts, so the entire cake 5×4 = 20 is the maximum piece.

Constraints

  • 2 ≤ h, w ≤ 109
  • 1 ≤ horizontalCuts.length, verticalCuts.length ≤ 105
  • 1 ≤ horizontalCuts[i] < h
  • 1 ≤ verticalCuts[i] < w
  • All the elements in horizontalCuts are distinct
  • All the elements in verticalCuts are distinct

Visualization

Tap to expand
Maximum Area of Cake After Cuts INPUT Cake: 5 x 4 h=1 h=2 h=4 v=1 v=3 h=5, w=4 hCuts=[1,2,4] vCuts=[1,3] ALGORITHM STEPS 1 Sort cuts arrays Add 0 and edges hCuts: [0,1,2,4,5] vCuts: [0,1,3,4] 2 Find max H gap Gaps: 1,1,2,1 maxH = max(1,1,2,1) = 2 3 Find max V gap Gaps: 1,2,1 maxV = max(1,2,1) = 2 4 Calculate area maxH * maxV mod 10^9+7 area = 2 * 2 = 4 Complexity Time: O(n log n + m log m) Space: O(1) FINAL RESULT 2x2 MAX Max Piece OUTPUT 4 Max area = 2 x 2 = 4 Result: 4 mod (10^9+7) = 4 Key Insight: The maximum cake piece area is determined by the largest horizontal gap multiplied by the largest vertical gap. Sort cuts, add boundaries (0, h) and (0, w), then find consecutive differences. No need to check all rectangles - just find maxH and maxV independently. O(n log n) solution. TutorialsPoint - Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts | Optimal Solution --> -->
Asked in
Google 12 Amazon 8 Facebook 6
98.4K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen