力扣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;
      }
  };
相关推荐
Tisfy15 小时前
LeetCode 0085.最大矩形:单调栈
算法·leetcode·题解·单调栈
mit6.82415 小时前
出入度|bfs|状压dp
算法
hweiyu0015 小时前
强连通分量算法:Kosaraju算法
算法·深度优先
源代码•宸15 小时前
Golang语法进阶(定时器)
开发语言·经验分享·后端·算法·golang·timer·ticker
mit6.82416 小时前
逆向思维|memo
算法
机器学习之心16 小时前
MATLAB灰狼优化算法(GWO)改进物理信息神经网络(PINN)光伏功率预测
神经网络·算法·matlab·物理信息神经网络
代码游侠16 小时前
学习笔记——ESP8266 WiFi模块
服务器·c语言·开发语言·数据结构·算法
倦王16 小时前
力扣日刷26110
算法·leetcode·职场和发展
涛涛北京16 小时前
【算法比较】
算法
yuniko-n16 小时前
【牛客面试 TOP 101】链表篇(二)
算法·链表·职场和发展