矩形蛋糕的高度为 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);
- }
- }
这种算法有没有问题,能保证长和宽同时为最大吗?欢迎到评论区讨论。