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

相关推荐
_深海凉_11 分钟前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展
故事还在继续吗18 分钟前
C++20关键特性
开发语言·c++·c++20
青少儿编程课堂1 小时前
2026青少儿信息素养大赛备赛指南!Python/Scratch/C++备考要点
开发语言·c++·python
踩坑记录1 小时前
leetcode hot100 寻找两个正序数组的中位数 hard 二分查找 双指针
leetcode
旖-旎1 小时前
深搜练习(电话号码字母组合)(3)
c++·算法·力扣·深度优先遍历
AIFarmer1 小时前
【无标题】
开发语言·c++·算法
John_ToDebug2 小时前
WebHostView 与 TabStrip 交互机制深度解析
c++·chrome·windows
南境十里·墨染春水3 小时前
C++笔记 STL——set
开发语言·c++·笔记
dgaf3 小时前
DX12 快速教程(17) —— 立体图标与合并渲染
c语言·c++·3d·图形渲染·d3d12
superior tigre4 小时前
78 子集
算法·leetcode·深度优先·回溯