当前位置:首页 > 编程笔记 > 正文
已解决

【Leetcode】【每日一题】【中等】1465. 切割后面积最大的蛋糕

来自网友在路上 192892提问 提问时间:2023-10-28 13:36:38阅读次数: 92

最佳答案 问答题库928位专家为你答疑解惑


力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。icon-default.png?t=N7T8https://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);}
}

结论

这种算法有没有问题,能保证长和宽同时为最大吗?欢迎到评论区讨论。

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"【Leetcode】【每日一题】【中等】1465. 切割后面积最大的蛋糕":http://eshow365.cn/6-26833-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!