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

相关推荐
元亓亓亓1 小时前
LeetCode热题100--79. 单词搜索
算法·leetcode·职场和发展
FuckPatience2 小时前
C++ 常用类型写法和全称
开发语言·c++
2501_941143732 小时前
缓存中间件Redis与Memcached在高并发互联网系统优化与实践经验分享
leetcode
__BMGT()3 小时前
参考文章资源记录
开发语言·c++·qt
ouliten3 小时前
C++笔记:std::string_view
开发语言·c++·笔记
玫瑰花店3 小时前
万字C++中锁机制和内存序详解
开发语言·c++·算法
D_evil__3 小时前
[C++高频精进] 文件IO:文件流
c++
西幻凌云3 小时前
认识STL序列式容器——List
开发语言·c++·stl·list·序列式容器
Elias不吃糖4 小时前
LeetCode每日一练(209, 167)
数据结构·c++·算法·leetcode
Want5954 小时前
C/C++跳动的爱心②
c语言·开发语言·c++