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

相关推荐
ZouZou老师10 小时前
C++设计模式之工厂方法模式:以家具生产为例
c++·设计模式·工厂方法模式
fish_xk13 小时前
c++中的引用和数组
开发语言·c++
有点。16 小时前
C++ ⼀级 2024 年 03 ⽉
c++
CC.GG17 小时前
【C++】二叉搜索树
java·c++·redis
Savior`L18 小时前
二分算法及常见用法
数据结构·c++·算法
深海潜水员18 小时前
OpenGL 学习笔记 第一章:绘制一个窗口
c++·笔记·学习·图形渲染·opengl
mmz120718 小时前
前缀和问题(c++)
c++·算法·图论
ULTRA??18 小时前
初学protobuf,C++应用例子(AI辅助)
c++·python
旖旎夜光19 小时前
list实现(7)(上)
c++
努力学算法的蒟蒻19 小时前
day27(12.7)——leetcode面试经典150
算法·leetcode·面试