力扣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;
      }
  };
相关推荐
noipp1 分钟前
推荐题目:洛谷 B2099 矩阵交换行
线性代数·算法·矩阵
五条凪2 小时前
简单理解 BM25 与 TF-IDF
人工智能·算法·搜索引擎·全文检索·tf-idf
行者全栈架构师2 小时前
【码动四季】Spring Boot 可观测性体系:Micrometer + OpenTelemetry + Grafana 全链路搭建
java·算法·架构
TCW11212 小时前
AI底层系列:用C++实现线性代数的公式推导与算法设计-8.线性变化(3)
c++·人工智能·算法
皓月斯语3 小时前
B3849 [GESP样题 三级] 进制转换 题解
c++·算法·题解
中微极客3 小时前
剪枝与量化:让YOLO在边缘设备上高效部署
算法·yolo·剪枝
牢姐与蒯3 小时前
双指针算法
数据结构·算法
Hesionberger3 小时前
LeetCode406:重建身高队列精髓解析
开发语言·数据结构·python·算法·leetcode
SweetCode4 小时前
交叉注意力机制
人工智能·python·深度学习·神经网络·算法