【每日一题Day224】LC2517礼盒的最大甜蜜度 | 二分答案

简介: 【每日一题Day224】LC2517礼盒的最大甜蜜度 | 二分答案

礼盒的最大甜蜜度【LC2517】

You are given an array of positive integers price where price[i] denotes the price of the ith candy and a positive integer k.


The store sells baskets of k distinct candies. The tastiness of a candy basket is the smallest absolute difference of the prices of any two candies in the basket.


Return the maximum tastiness of a candy basket.

最大化最小化类似题目

  • 思路:使用二分查找的方式寻找最大甜蜜度
  • 本题的单调性为:当**最小甜蜜度【数组中任意两个元素的差值的绝对值的最小值】**越大,糖果的可以选择的种类越小【选取的数组中的元素个数】,因此可以通过二分查找法找到最终答案

将题意转化为:当选取的数量一定时,寻找最小甜蜜度的最大值y ,二分查找的下限为0,上限为数组中最大元素与最小元素的差值/(k-1)

  • 实现
  • 首先对price数组进行升序排序

image.png

class Solution {
    public int maximumTastiness(int[] price, int k) {
        Arrays.sort(price);
        int n = price.length;
        int l = 0, r = price[n - 1] - price[0];
        int ans = 0;
        while (l <= r){
            int mid = (r + l) / 2;
            if (check(price, mid ,k)){
                ans = mid;
                l = mid + 1;
            }else{
                r = mid - 1;
            }
        }
        return ans;
    }
    public boolean check(int[] price, int m, int k){
        int count = 1;
        int preIndex = 0;
        for (int i = 1; i < price.length; i++){
            if (price[i] - price[preIndex] >= m ){
                count++;
                preIndex = i;
            }
        }
        return count >= k;
    }
}

image.png


目录
相关文章
|
2月前
|
算法
【每日一题Day363】LC275H 指数Ⅱ | 二分答案
【每日一题Day363】LC275H 指数Ⅱ | 二分答案
39 0
|
2月前
【每日一题Day312】LC2240买钢笔和铅笔的方案数 | 完全背包 数学
【每日一题Day312】LC2240买钢笔和铅笔的方案数 | 完全背包 数学
38 0
|
2月前
|
机器学习/深度学习
【每日一题Day125】LC1326灌溉花园的最少水龙头数目 | 动态规划 贪心
【每日一题Day125】LC1326灌溉花园的最少水龙头数目 | 动态规划 贪心
38 0
|
2月前
【每日一题Day167】LC1000合并石头的最低成本 | 区间dp
【每日一题Day167】LC1000合并石头的最低成本 | 区间dp
36 1
【每日一题Day167】LC1000合并石头的最低成本 | 区间dp
|
2月前
【每日一题Day154】LC1626无矛盾的最佳球队 | 动态规划
【每日一题Day154】LC1626无矛盾的最佳球队 | 动态规划
25 0
|
2月前
【每日一题Day362】LC274H 指数 | 二分答案
【每日一题Day362】LC274H 指数 | 二分答案
22 0
|
2月前
【每日一题Day330】LC337打家劫舍Ⅲ | 动态规划
【每日一题Day330】LC337打家劫舍Ⅲ | 动态规划
24 0
|
2月前
【每日一题Day126】LC1140石子游戏Ⅱ | 博弈dp 记忆化搜索
【每日一题Day126】LC1140石子游戏Ⅱ | 博弈dp 记忆化搜索
35 0
|
2月前
|
存储 算法
【每日一题Day310】LC1654到家的最少跳跃次数 | BFS
【每日一题Day310】LC1654到家的最少跳跃次数 | BFS
25 0
|
2月前
【每日一题Day319】LC2594修车的最少时间 | 二分答案
【每日一题Day319】LC2594修车的最少时间 | 二分答案
21 0