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

medium array greedy sorting

Problem

A rectangular cake of size h × w. Given horizontalCuts (y-values) and verticalCuts (x-values), return the maximum piece area after all cuts, modulo 10^9+7.

Inputh=5, w=4, horizontalCuts=[1,2,4], verticalCuts=[1,3]
Output4
Largest gaps: horizontal 2 (between 2 and 4), vertical 2 (between 1 and 3) → 4.

def max_area(h, w, hc, vc):
    MOD = 10**9 + 7
    def biggest(arr, total):
        a = sorted(arr); best = a[0]; prev = a[0]
        for v in a[1:]:
            best = max(best, v - prev); prev = v
        return max(best, total - a[-1])
    return biggest(hc, h) * biggest(vc, w) % MOD
function maxArea(h, w, hc, vc) {
  const MOD = 1_000_000_007n;
  function biggest(arr, total) {
    const a = arr.slice().sort((x, y) => x - y);
    let best = a[0], prev = a[0];
    for (let i = 1; i < a.length; i++) { best = Math.max(best, a[i] - prev); prev = a[i]; }
    return Math.max(best, total - a[a.length - 1]);
  }
  return Number(BigInt(biggest(hc, h)) * BigInt(biggest(vc, w)) % MOD);
}
class Solution {
    public int maxArea(int h, int w, int[] hc, int[] vc) {
        long MOD = 1_000_000_007L;
        return (int)(((long) gap(hc, h)) * gap(vc, w) % MOD);
    }
    int gap(int[] a, int total) {
        Arrays.sort(a);
        int best = a[0], prev = a[0];
        for (int i = 1; i < a.length; i++) { best = Math.max(best, a[i] - prev); prev = a[i]; }
        return Math.max(best, total - a[a.length - 1]);
    }
}
int maxArea(int h, int w, vector& hc, vector& vc) {
    long long MOD = 1000000007LL;
    auto gap = [](vector& a, int total) {
        sort(a.begin(), a.end());
        int best = a[0], prev = a[0];
        for (int i = 1; i < (int)a.size(); i++) { best = max(best, a[i] - prev); prev = a[i]; }
        return max(best, total - a.back());
    };
    return (int)((long long) gap(hc, h) * gap(vc, w) % MOD);
}
Time: O((m+n) log(m+n)) Space: O(1)