Sponsored
Sponsored
This approach involves sorting the cut arrays and finding the maximum gaps between consecutive cuts, including the edges of the cake. Once the maximum horizontal and vertical gaps are identified, the maximum possible area of a piece of cake can be obtained by multiplying these two maximum gaps.
Time Complexity: O(n log n + m log m), where n and m are the sizes of the horizontalCuts and verticalCuts arrays, due to sorting.
Space Complexity: O(1) additional space is used, as computations are done in-place.
1function maxArea(h, w, horizontalCuts, verticalCuts) {
2 const MOD = 1e9 + 7;
3 horizontalCuts.sort((a, b) => a - b);
4 verticalCuts.sort((a, b) => a - b);
5 let maxH = Math.max(horizontalCuts[0], h - horizontalCuts[horizontalCuts.length - 1]);
6 let maxW = Math.max(verticalCuts[0], w - verticalCuts[verticalCuts.length - 1]);
7
8 for (let i = 1; i < horizontalCuts.length; i++) {
9 maxH = Math.max(maxH, horizontalCuts[i] - horizontalCuts[i - 1]);
10 }
11 for (let i = 1; i < verticalCuts.length; i++) {
12 maxW = Math.max(maxW, verticalCuts[i] - verticalCuts[i - 1]);
13 }
14 return (maxH * maxW) % MOD;
15}
JavaScript employs array sorting with a comparison function. Maximum differences between edges and each consecutive cut define the largest piece of cake obtainable after cuts, and the area is calculated using modulo arithmetic.
This approach uses dynamic programming to store previously calculated results for maximum gaps between cuts, optimizing repeated calculations by using memoization. This is particularly useful when recalculating maximum differences thousands of times for larger input sizes.
Time Complexity: O(n log n + m log m) for sorting; O(n + m) in constant time queries after sorting using memo.
Space Complexity: O(n + m) for memoization storage.
1def maxAreaDP(h, w, horizontalCuts, verticalCuts
The Python DP solution stores results of maximum gap calculations in a dictionary (memo) to avoid repeated computation. It defines a helper function getMaxGap()
for finding the largest segment gap using the memoization pattern. This stores every result fetched per list, speeding up subsequent gap queries.