Taro Logo

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

Medium
Asked by:
IXL
BNY
2 views
Topics:
ArraysGreedy Algorithms

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 ith horizontal cut and similarly, and
  • verticalCuts[j] is the distance from the left of the rectangular cake to the jth 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 109 + 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 <= 109
  • 1 <= horizontalCuts.length <= min(h - 1, 105)
  • 1 <= verticalCuts.length <= min(w - 1, 105)
  • 1 <= horizontalCuts[i] < h
  • 1 <= verticalCuts[i] < w
  • All the elements in horizontalCuts are distinct.
  • All the elements in verticalCuts are distinct.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Are the `horizontalCuts` and `verticalCuts` arrays guaranteed to be sorted in ascending order when passed into the function?
  2. Could the cut positions in the arrays contain duplicates, or are all given cut positions guaranteed to be unique?
  3. What should be the expected return value if the arrays of cuts are empty?
  4. Are the values in `horizontalCuts` and `verticalCuts` guaranteed to be strictly within the bounds of the cake's height and width (i.e., strictly between 0 and `h` / `w`), or could they include the edges?
  5. Since the maximum area can be very large, should we return the result modulo $10^9 + 7$?

Brute Force Solution

Approach

Imagine you have a large sheet of paper and you need to make several horizontal and vertical cuts to see which resulting piece has the biggest area. The brute force strategy involves actually making every possible combination of cuts, creating every single little piece of cake, and then measuring them all to find the biggest one.

Here's how the algorithm would work step-by-step:

  1. Start by looking at all the given locations where horizontal cuts can be made, and all the locations where vertical cuts can be made.
  2. Simulate making every possible pair of horizontal cuts together with every possible pair of vertical cuts.
  3. Every time you choose a pair of horizontal cuts and a pair of vertical cuts, carve out that specific rectangular piece of the sheet.
  4. Calculate the area of that newly formed piece by multiplying its width by its height.
  5. Do this for every single combination of cuts, effectively checking every possible piece that can be created from the sheet.
  6. Keep a mental note of the largest area you have found so far, updating it whenever you measure a piece that is bigger than your current record.
  7. Once you have checked every single possible combination of cuts, the record you kept of the biggest area will be your final answer.

Code Implementation

def max_area(cake_height, cake_width, horizontal_cuts, vertical_cuts):
    # We add the boundaries of the cake to properly evaluate all regions
    full_horizontal = [0] + sorted(horizontal_cuts) + [cake_height]
    full_vertical = [0] + sorted(vertical_cuts) + [cake_width]

    maximum_area_found = 0

    # Iterate through all cut combinations to test every possible rectangular piece
    for horizontal_start_index in range(len(full_horizontal)):
        for horizontal_end_index in range(horizontal_start_index + 1, len(full_horizontal)):
            for vertical_start_index in range(len(full_vertical)):
                for vertical_end_index in range(vertical_start_index + 1, len(full_vertical)):

                    piece_height = full_horizontal[horizontal_end_index] - full_horizontal[horizontal_start_index]
                    piece_width = full_vertical[vertical_end_index] - full_vertical[vertical_start_index]

                    current_piece_area = piece_height * piece_width

                    # Track the largest area found so far among all generated pieces
                    if current_piece_area > maximum_area_found:
                        maximum_area_found = current_piece_area

    # Apply modulo constraint to prevent integer overflow for large outputs
    return maximum_area_found % 1000000007

Big(O) Analysis

Time Complexity
O(H^2 * V^2) – To evaluate every possible piece, we must iterate through all pairs of horizontal cuts and all pairs of vertical cuts using nested loops. If there are H horizontal cuts and V vertical cuts, the loops will examine approximately (H * (H - 1) / 2) pairs of horizontal boundaries and (V * (V - 1) / 2) pairs of vertical boundaries. Multiplying these combinations together yields roughly (H^2 * V^2) / 4 total rectangle area calculations. Dropping the constants, this brute force approach simplifies to a time complexity of O(H^2 * V^2).
Space Complexity
O(1) – The brute force simulation relies entirely on local loop variables to iterate through every combination of horizontal and vertical cuts without allocating any additional dynamic data structures. Keeping a mental note of the largest area requires only a single primitive integer variable to track the running maximum. Because no temporary lists, arrays, or recursive stack frames are created to store intermediate pieces, the auxiliary memory footprint remains completely constant regardless of the number of cuts. Thus, the total extra memory required is independent of the input size, simplifying to a constant space complexity.

Optimal Solution

Approach

To find the largest piece of cake, we need to determine the single biggest vertical gap and the single biggest horizontal gap created by the cuts. Multiplying these two maximum gaps together gives the area of the largest possible piece.

Here's how the algorithm would work step-by-step:

  1. Begin by organizing all the horizontal cut locations in order from top to bottom, and include the very top edge and very bottom edge of the cake as boundaries.
  2. Do the same for the vertical cuts, organizing them from left to right, and include the far left and far right edges of the cake as boundaries.
  3. Compare the distances between every adjacent pair of horizontal boundaries to find the widest vertical gap.
  4. Compare the distances between every adjacent pair of vertical boundaries to find the widest horizontal gap.
  5. Multiply the maximum vertical gap by the maximum horizontal gap to find the area of the largest piece.
  6. Because the result can be very large, adjust the final number by dividing it according to standard rules to keep it manageable before sharing the answer.

Code Implementation

def max_area(cake_height, cake_width, horizontal_cuts, vertical_cuts):
    # Adding boundaries is necessary to measure the gaps from edges to the first cuts.
    horizontal_cuts.extend([0, cake_height])
    vertical_cuts.extend([0, cake_width])

    horizontal_cuts.sort()
    vertical_cuts.sort()

    max_horizontal_gap = 0
    for index in range(1, len(horizontal_cuts)):
        current_gap = horizontal_cuts[index] - horizontal_cuts[index - 1]
        if current_gap > max_horizontal_gap:
            max_horizontal_gap = current_gap

    max_vertical_gap = 0
    for index in range(1, len(vertical_cuts)):
        current_gap = vertical_cuts[index] - vertical_cuts[index - 1]
        if current_gap > max_vertical_gap:
            max_vertical_gap = current_gap

    # Multiplying max dimensions finds the area of the single largest resulting piece.
    maximum_area = max_horizontal_gap * max_vertical_gap

    # Modulo is required because the area can be excessively large for memory limits.
    return maximum_area % 1000000007

Big(O) Analysis

Time Complexity
O(h log h + v log v) – The time complexity is driven by sorting the horizontal cuts of size h and the vertical cuts of size v to establish the boundary order. Specifically, sorting the horizontal cuts takes O(h log h) time and sorting the vertical cuts takes O(v log v) time. Afterward, making a single linear pass through each sorted array to find the maximum gaps takes O(h) and O(v) time respectively. Combining these steps, the total operations approximate h log h + v log v + h + v, which simplifies to O(h log h + v log v).
Space Complexity
O(H + V) – Steps 1 and 2 require organizing the horizontal and vertical cuts by adding the cake boundaries and sorting them. Assuming the cuts are not already sorted, storing the sorted lists of horizontal and vertical positions takes extra space proportional to the number of horizontal cuts and vertical cuts. Letting H be the number of horizontal cuts and V be the number of vertical cuts, this requires auxiliary storage of size O(H + V). Beyond these sorting structures, only a few primitive variables are used to track maximum gaps, resulting in a final auxiliary space complexity of O(H + V).

Edge Cases

Cuts provided in unsorted order
How to Handle:
We must explicitly sort both the horizontal and vertical cut arrays before calculating differences.
Cuts at the exact boundaries of the cake such as 0 or the max height and width
How to Handle:
Prepend 0 and append the cake dimension (height or width) to the respective cut arrays to include boundary intervals.
Arrays containing duplicate cut values
How to Handle:
Sorting and computing adjacent differences naturally yields a difference of zero for duplicates, ignoring redundant cuts safely.
Minimum possible cake dimensions with no intermediate cuts
How to Handle:
Defaulting the boundary prepending and appending ensures we correctly calculate the area as the full height multiplied by the full width.
Maximum possible dimensions and cut array lengths up to 10^5
How to Handle:
An O(N log N) sorting approach combined with a linear pass scales efficiently and easily passes within time limits.
Integer overflow during the multiplication of the maximum horizontal and vertical gaps
How to Handle:
We must cast the maximum differences to 64-bit integers and apply the modulo operation 10^9 + 7 to the product before returning.