Leetcode3219. 切蛋糕的最小总开销 II

Every day a Leetcode

题目来源:3219. 切蛋糕的最小总开销 II

解法1:贪心

谁的开销更大,就先切谁,并且这个先后顺序与切的次数无关。

代码:

c 复制代码
/*
 * @lc app=leetcode.cn id=3219 lang=cpp
 *
 * [3219] 切蛋糕的最小总开销 II
 */

// @lc code=start
class Solution
{
public:
    long long minimumCost(int m, int n, vector<int> &horizontalCut, vector<int> &verticalCut)
    {
        sort(horizontalCut.begin(), horizontalCut.end(), greater<int>());
        sort(verticalCut.begin(), verticalCut.end(), greater<int>());

        long long ans = 0;
        int cnt_h = 1, cnt_v = 1;
        int i = 0, j = 0;
        while (i < m - 1 || j < n - 1)
        {
            if (j == n - 1 || i < m - 1 && horizontalCut[i] > verticalCut[j])
            {
                ans += horizontalCut[i++] * cnt_h; // 横切
                cnt_v++;                           // 需要竖切的蛋糕块增加
            }
            else
            {
                ans += verticalCut[j++] * cnt_v; // 竖切
                cnt_h++;                         // 需要横切的蛋糕块增加
            }
        }
        return ans;
    }
};
// @lc code=end

结果:

复杂度分析:

时间复杂度:O(mlogm+nlogn),瓶颈在排序上。

空间复杂度:O(1)。

相关推荐
郭源潮114 小时前
《Muduo网络库:实现TcpServer类终章》
服务器·网络·c++·网络库
夏鹏今天学习了吗17 小时前
【LeetCode热题100(56/100)】组合总和
算法·leetcode·职场和发展
微笑尅乐17 小时前
三种方法解开——力扣3370.仅含置位位的最小整数
python·算法·leetcode
MMjeaty17 小时前
查找及其算法
c++·算法
yong158585534318 小时前
1. Linux C++ muduo 库学习——库的编译安装
linux·c++·学习
mit6.82419 小时前
回溯剪枝trick
c++
渡我白衣20 小时前
C++世界的混沌边界:undefined_behavior
java·开发语言·c++·人工智能·深度学习·语言模型
却道天凉_好个秋20 小时前
c++ 协程
c++
无敌最俊朗@1 天前
视频时间基 (time_base) 详解:时间的“刻度单位”
c++
脏脏a1 天前
【C++ 入门】:引用、内联函数与 C++11 新特性(auto、范围 for、nullptr)全解析
开发语言·c++