力扣2517.礼盒的最大甜蜜度

力扣2517.礼盒的最大甜蜜度

  • 二分答案求最小值

    • 排完序判断是否有k个差距至少为mid的元素
    • 别用i遍历 可能会越界 用 : 有多少取多少
cpp 复制代码
  class Solution {
  public:
      int maximumTastiness(vector<int>& price, int k) {
          ranges::sort(price);
          auto check = [&](int mid) -> bool
          {
              int res=1,pre = price[0];
              for(auto p : price)
              {
                  if(p >= pre + mid)
                  {
                      pre = p;
                      res++;
                  }
              }
              return res >= k;
          };
          int l = 0,r = ranges::max(price);
          while(l<r)
          {
              int mid = l + r + 1>> 1;
              if(check(mid)) l = mid;
              else r = mid - 1;
          }
          return l;
      }
  };
相关推荐
Frostnova丶14 小时前
【算法笔记】数学知识
笔记·算法
吴可可12314 小时前
AutoCAD 2016与2014二次开发关键差异
算法
雨白15 小时前
哈希:以时间换空间的算法实战
算法
San813_LDD17 小时前
[数据结构]LeetCode学习
数据结构·算法·图论
x1387028595717 小时前
c语言排雷游戏(基础版9*9)
c语言·算法·游戏
sheeta199818 小时前
LeetCode 每日一题笔记 日期:2026.06.06 题目:2196. 根据描述创建二叉树
笔记·算法·leetcode
小欣加油19 小时前
leetcode994 腐烂的橘子
数据结构·c++·算法·leetcode·bfs
QuZero19 小时前
Guava Cache Deep Dive
java·后端·算法·guava
随意起个昵称19 小时前
线性dp-LIS题目4(A Twisty Movement)
算法·动态规划