Woodyiiiiiii / LeetCode

My private record of Leetcode solution

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Leetcode 2517. Maximum Tastiness of Candy Basket

Woodyiiiiiii opened this issue · comments

2517. Maximum Tastiness of Candy Basket

相关题目

这道题一开始完全想不到二分,不知道怎么应用二分。

这时候要用反向思维,把答案作为二分的轴。

先要排序,排除掉数组元素位置的影响。因为目的是找到之前差值大于等于这个轴的元素。

同时注意l包含,r不包含,所有r左移是r=mid;返回值直接是l-1。

class Solution {
    public int maximumTastiness(int[] price, int k) {
        Arrays.sort(price);

        int l = 0, r = 1000000000;
        while (l < r) {
            int mid = (l + r) >> 1;
            if (check(price, k, mid)) {
                l = mid + 1;
            } else {
                r = mid;
            }
        }
        
        return l - 1;
    }

    boolean check(int[] price, int k, int mid) {
        int cnt = 1;
        int last = price[0];
        int kk = 1;
        while (kk < price.length && cnt < k) {
            if (price[kk] - last >= mid) {
                ++cnt;
                last = price[kk];
            }
            ++kk;
        }
        return cnt == k;
    }

}

tips:

  1. 发现,对于结果是l-1还是l,根据check函数分支来判断,如果是l = mid + 1则是l-1,否则r=mid则是l
  2. 一般二分的使用场景是有题目条件变量范围特别大,比如到1e9
  3. check函数大部分可能用到数学知识,或者剪枝,还有贪心,用来尽可能缩减时间