力扣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;
      }
  };
相关推荐
有意义2 小时前
深度拆解分割等和子集:一维DP数组与倒序遍历的本质
前端·算法·面试
xlp666hub3 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
用户726876103373 小时前
解放双手的健身助手:基于 Rokid AR 眼镜的运动计时应用
算法
Wect4 小时前
LeetCode 17. 电话号码的字母组合:回溯算法入门实战
前端·算法·typescript
xlp666hub20 小时前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
程序员小崔日记1 天前
大三备战考研 + 找实习:我整理了 20 道必会的时间复杂度题(建议收藏)
算法·408·计算机考研
lizhongxuan1 天前
AI小镇 - 涌现
算法·架构
AI工程架构师1 天前
通常说算力是多少 FLOPS,怎么理解,GPU和CPU为什么差异这么大
算法
祈安_1 天前
Java实现循环队列、栈实现队列、队列实现栈
java·数据结构·算法