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

相关推荐
虾球xz37 分钟前
游戏引擎学习第268天:合并调试链表与分组
c++·学习·链表·游戏引擎
fpcc1 小时前
跟我学c++高级篇——模板元编程之十三处理逻辑
c++
格林威2 小时前
Baumer工业相机堡盟工业相机的工业视觉中为什么偏爱“黑白相机”
开发语言·c++·人工智能·数码相机·计算机视觉
Dream it possible!3 小时前
LeetCode 热题 100_只出现一次的数字(96_136_简单_C++)(哈希表;哈希集合;排序+遍历;位运算)
c++·leetcode·位运算·哈希表·哈希集合
Dddle14 小时前
C++:this指针
java·c语言·开发语言·c++
不見星空5 小时前
2025年第十六届蓝桥杯软件赛省赛C/C++大学A组个人解题
c语言·c++·蓝桥杯
jiunian_cn5 小时前
【c++】异常详解
java·开发语言·数据结构·c++·算法·visual studio
梁下轻语的秋缘5 小时前
每日c/c++题 备战蓝桥杯(洛谷P1387 最大正方形)
c语言·c++·蓝桥杯
熬夜学编程的小王5 小时前
【C++进阶篇】多态
c++·多态·静态绑定与动态绑定
UpUpUp……5 小时前
Linux--JsonCpp
linux·运维·服务器·c++·笔记·json