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

相关推荐
White_Can7 分钟前
《C++11:智能指针》
c++·c++11·智能指针
无限进步_8 分钟前
【数据结构&C语言】对称二叉树的递归之美:镜像世界的探索
c语言·开发语言·数据结构·c++·算法·github·visual studio
im_AMBER20 分钟前
Leetcode 98 从链表中移除在数组中存在的节点
c++·笔记·学习·算法·leetcode·链表
CSDN_RTKLIB20 分钟前
C++取模与取余
开发语言·c++
星河耀银海37 分钟前
C++开发入门——环境搭建与第一个程序
开发语言·c++·策略模式
漫随流水1 小时前
leetcode算法(429.N叉树的层序遍历)
数据结构·算法·leetcode·二叉树
漫随流水2 小时前
leetcode算法(116.填充每个节点的下一个右侧节点指针)
数据结构·算法·leetcode·二叉树
_OP_CHEN2 小时前
【算法基础篇】(四十四)数论之欧拉定理与扩展欧拉定理深度解析:从降幂到超大规模幂运算
c++·算法·蓝桥杯·算法竞赛·欧拉定理·扩展欧拉定理·acm/icpc
liulilittle2 小时前
DeepWiki: OPENPPP2 工程价值
网络·c++·网络协议·ai·信息与通信·通信
星河耀银海2 小时前
C++面向对象编程:从基础到实战
开发语言·c++