力扣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;
      }
  };
相关推荐
Jerry1 小时前
LeetCode 459. 重复的子字符串
算法
海石4 小时前
1500分的题目,确实有实力,不过还是我略胜一筹
算法·leetcode
海石4 小时前
【记忆化搜索】条条大路通AC,走好适合你的那一条,走到后再考虑走得快
算法·leetcode
Jerry6 小时前
LeetCode 151. 反转字符串中的单词
算法
咖啡星人k8 小时前
从Vibe Coding到Prompt Engineering:AI编程的新技能树
面试·职场和发展·ai编程
a1117768 小时前
LM 算法迭代过程动画演示(SLAM)
算法
头茬韭菜8 小时前
Context 的生死抉择:四层压缩、截断算法与 Session Memory
算法·ai
Jerry8 小时前
LeetCode 541. 反转字符串 II
算法
Jerry9 小时前
LeetCode 344. 反转字符串
算法
搞科研的小刘选手9 小时前
【香港大学主办&IEEE出版】第六届计算机视觉、应用与算法国际学术会议(CVAA 2026)
算法·计算机视觉·应用·学术会议