力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。 https://leetcode.cn/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/description/?envType=daily-question&envId=2023-10-27
https://leetcode.cn/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/description/?envType=daily-question&envId=2023-10-27
矩形蛋糕的高度为 h 且宽度为 w,给你两个整数数组 horizontalCuts 和 verticalCuts,其中:
-  horizontalCuts[i]是从矩形蛋糕顶部到第i个水平切口的距离
- verticalCuts[j]是从矩形蛋糕的左侧到第- j个竖直切口的距离
请你按数组 horizontalCuts 和 verticalCuts 中提供的水平和竖直位置切割后,请你找出 面积最大 的那份蛋糕,并返回其 面积 。由于答案可能是一个很大的数字,因此需要将结果 对 109 + 7 取余 后返回。

自己的思路
贪心思想,找最大的长和宽,如下图所示,2*2=4即为所求。

可是我感觉该算法有问题,不能同时保证最大的长对应最大的宽。我用下面有问题的代码,通过了Leetcode...
class Solution {
    public int calMax(int t, int[] data) {
        int h_len = data.length;
        ArrayList arrayList = new ArrayList<>();
        arrayList.add(data[0] - 0);
        arrayList.add(t - data[h_len - 1]);
        for (int i = h_len - 1; i >= 1; i--) {
            arrayList.add(data[i] - data[i - 1]);
        }
        return (Integer)Collections.max(arrayList);
    }
    public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) {
        Arrays.sort(horizontalCuts);
        Arrays.sort(verticalCuts);
        long x = calMax(h, horizontalCuts);
        long y = calMax(w, verticalCuts);
        return (int) ((x * y) % 1000000007);
    }
}
力扣官方题解
感觉和上面的贪心算法一模一样,感觉有点问题
class Solution {
    public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) {
        Arrays.sort(horizontalCuts);
        Arrays.sort(verticalCuts);
        return (int) ((long) calMax(horizontalCuts, h) * calMax(verticalCuts, w) % 1000000007);
    }
    public int calMax(int[] arr, int boardr) {
        int res = 0, pre = 0;
        for (int i : arr) {
            res = Math.max(i - pre, res);
            pre = i;
        }
        return Math.max(res, boardr - pre);
    }
}结论
这种算法有没有问题,能保证长和宽同时为最大吗?欢迎到评论区讨论。


















![C++in/out输入输出流[IO流]](https://img-blog.csdnimg.cn/af6a05879b954ef18a19a91e0cbf5f57.png)
