VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-area-of-a-cake-after-horizontal-and-vertical-cuts/

⇱ Maximum area of a Cake after Horizontal and Vertical cuts - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum area of a Cake after Horizontal and Vertical cuts

Last Updated : 24 Feb, 2025

Given two positive integers h and w representing the height and width of a rectangle. Additionally, we have two arrays, horizontalCuts and verticalCuts, where:

  • horizontalCuts[i] is the distance from the top of the rectangular cake to the i-th horizontal cut.
  • verticalCuts[i] is the distance from the left of the rectangular cake to the j-th vertical cut.

The task is to find the maximum area of the rectangle after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts.

Examples: 

Input: h = 6, w = 4, horizontalCuts = [2, 5], verticalCuts = [1, 3]
Output: 6
Explanation: The figure below represents the given rectangle.
👁 2geeksforgeek

Red lines are the horizontal cuts and blue lines are vertical cuts. After the rectangle is cut, the green piece of rectangle has the maximum area.

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

[Expected Approach] Using Sorting - O(n * log(n) + m * log(m)) Time and O(1) Space

The idea is to maximize the area of a rectangular piece formed by the cuts. Since the largest area is determined by the widest horizontal and vertical gaps, we first sort the cut positions and find the maximum gaps between consecutive cuts. The final area is obtained by multiplying the largest horizontal gap with the largest vertical gap. Sorting ensures efficient gap calculation, making the approach optimal.

Steps to implement the above idea:

  • Sort horizontalCuts and verticalCuts in ascending order to process them efficiently.
  • Append h and w to their respective lists to ensure the last segment is considered.
  • Initialize maxHorizontal and maxVertical with the first cut size to handle the first segment.
  • Iterate through horizontalCuts and verticalCuts to find the maximum gap between consecutive cuts.
  • Multiply the largest horizontal gap with the largest vertical gap to get the maximum area.
  • Return the computed maximum area, which represents the largest rectangular piece after the cuts.

Output
6


Comment
Article Tags: