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

相关推荐
AA陈超41 分钟前
虚幻引擎5 GAS开发俯视角RPG游戏 P05-08 UI 部件数据表
c++·游戏·ue5·游戏引擎·虚幻
纵有疾風起2 小时前
C++——类和对象(3)
开发语言·c++·经验分享·开源
承渊政道3 小时前
动态内存管理
c语言·c++·经验分享·c#·visual studio
孤独得猿3 小时前
聊天室项目开发——etcd的安装和使用
linux·服务器·c++·etcd
new coder3 小时前
[c++语法学习]Day10:c++引用
开发语言·c++·学习
无敌最俊朗@4 小时前
数组-力扣hot56-合并区间
数据结构·算法·leetcode
哼?~5 小时前
C++11标准 上 (万字解析)
开发语言·c++
码农多耕地呗5 小时前
力扣94.二叉树的中序遍历(递归and迭代法)(java)
数据结构·算法·leetcode
给大佬递杯卡布奇诺5 小时前
FFmpeg 基本API avformat_alloc_context 函数内部调用流程分析
c++·ffmpeg·音视频
微笑尅乐5 小时前
BFS 与 DFS——力扣102.二叉树的层序遍历
leetcode·深度优先·宽度优先