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)。

相关推荐
踩坑记录4 小时前
leetcode hot100 2.两数相加 链表 medium
leetcode·链表
qq_192779875 小时前
C++模块化编程指南
开发语言·c++·算法
代码村新手5 小时前
C++-String
开发语言·c++
历程里程碑7 小时前
滑动窗口---- 无重复字符的最长子串
java·数据结构·c++·python·算法·leetcode·django
2501_940315268 小时前
航电oj:首字母变大写
开发语言·c++·算法
lhxcc_fly8 小时前
手撕简易版的智能指针
c++·智能指针实现
TracyCoder1238 小时前
LeetCode Hot100(18/100)——160. 相交链表
算法·leetcode
浒畔居8 小时前
泛型编程与STL设计思想
开发语言·c++·算法
Fcy6488 小时前
C++ 异常详解
开发语言·c++·异常
机器视觉知识推荐、就业指导9 小时前
Qt 和 C++,是不是应该叫 Q++ 了?
开发语言·c++·qt