Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 2517. Maximum Tastiness of Candy Basket #164

Open
Woodyiiiiiii opened this issue Dec 28, 2022 · 0 comments
Open

Leetcode 2517. Maximum Tastiness of Candy Basket #164

Woodyiiiiiii opened this issue Dec 28, 2022 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Woodyiiiiiii commented Dec 28, 2022

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函数大部分可能用到数学知识,或者剪枝,还有贪心,用来尽可能缩减时间

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant