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

相关推荐
余额瞒着我当琳21 分钟前
红黑树的实现--红黑树的概念、规则、效率、结构、旋转、查找、验证
数据结构·c++·算法
青少儿编程课堂27 分钟前
AC自动机多模式串匹配精讲:校园关键词巡检实战解析
c++·python·算法·bfs·信息学竞赛
longlongzihan1 小时前
LeetCode 5. 最长回文子串:从暴力匹配到中心扩展的思维演进
c++·算法·leetcode
苦瓜打怪兽1 小时前
leetcode 热题100(11. 盛最多水的容器)
python·算法·leetcode
多弗朗皮卡丘1 小时前
C++继承
c++·继承
汉克老师2 小时前
GESP2026年9月认证C++七级( 第三部分编程题(2、括号序列))精讲
c++·gesp·小学生·学c++编程
jimy14 小时前
虚函数vtable,链接时看到构造函数,linker把符号地址写入vtable(三)
开发语言·c++
潼心1412o5 小时前
C++初阶(长期更新)第9讲:string(上)
开发语言·c++
朝朝辞暮i5 小时前
C++ 第 39 章: 阶段性总复习——类、对象、构造、继承、this、指针与智能指针
开发语言·c++·算法·ros2
wuminyu5 小时前
Virtual Thread重投递至ForkJoinPool任务队列过程解析
java·linux·c语言·jvm·c++