You are given a rectangular cake with height h and width w. You are also given two arrays: horizontalCuts and verticalCuts. These arrays represent the coordinates where you will slice the cake. After making all the cuts, the cake is divided into multiple smaller rectangular pieces. Your objective is to find the maximum area among all these resulting pieces, returning the answer modulo .
This is a visual geometry problem that tests a candidate's ability to decouple axes. Interviewers ask it because candidates who try to physically model the grid and calculate the area of every single resulting piece () will fail the time constraints. It evaluates whether you can deduce that the largest area is simply the product of the largest horizontal gap and the largest vertical gap.
This utilizes a Sorting and Greedy Gap pattern.
horizontalCuts array and the verticalCuts array.horizontalCuts to find the maximum difference between any two adjacent cuts. Don't forget to check the edges (distance from 0 to the first cut, and the last cut to h).verticalCuts to find the maximum width.Cake h = 5, w = 4.
horizontalCuts = [1, 2, 4]
verticalCuts = [1, 3]
Analyze horizontal gaps:
h) = gap 1
Max horizontal gap (height) = 2.Analyze vertical gaps:
w) = gap 1
Max vertical gap (width) = 2.The largest piece of cake has dimensions . Area is 4.
A very common mistake is forgetting to evaluate the boundary edges of the cake. Candidates often just loop arr[i] - arr[i-1] and completely forget that a piece of cake exists between the top edge 0 and the first cut, and between the last cut and the far edge h or w. Another mistake is multiplying the two large gaps using standard 32-bit integers, which will cause an overflow before the modulo is applied. You must cast them to long before multiplying.
For the Maximum Area of a Piece of Cake coding problem, write a clean helper function: long getMaxGap(int[] cuts, int maxEdge). Inside, sort the array, calculate maxGap = Math.max(cuts[0], maxEdge - cuts[cuts.length - 1]), then loop through the inner cuts. This shows strong software engineering principles (DRY code) and prevents copy-paste errors.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Array With Elements Not Equal to Average of Neighbors | Medium | Solve | |
| Destroying Asteroids | Medium | Solve | |
| Divide Array Into Arrays With Max Difference | Medium | Solve | |
| Eat Pizzas! | Medium | Solve | |
| Eliminate Maximum Number of Monsters | Medium | Solve |