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

相关推荐
Darkwanderor32 分钟前
高精度计算——基础模板整理
c++·算法·高精度计算
Tanecious.1 小时前
蓝桥杯备赛:Day5-P1036 选数
c++·蓝桥杯
py有趣1 小时前
力扣热门100题之接雨水
算法·leetcode
mmz12071 小时前
深度优先搜索DFS(c++)
c++·算法·深度优先
憧憬从前2 小时前
算法学习记录DAY1
c++·学习
A.A呐3 小时前
【C++第二十四章】异常
开发语言·c++
xiaoye-duck3 小时前
《算法题讲解指南:动态规划算法--子序列问题》--29.最长递增子序列的个数,30.最长数对链,31.最长定差子序列
c++·算法·动态规划
森G3 小时前
39、拓展知识---------事件系统
c++·qt
tankeven3 小时前
HJ164 太阳系DISCO
c++·算法
君鼎4 小时前
C++17 新特性全面总结
c++