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 2226. Maximum Candies Allocated to K Children #99

Open
Woodyiiiiiii opened this issue Apr 10, 2022 · 0 comments
Open

LeetCode 2226. Maximum Candies Allocated to K Children #99

Woodyiiiiiii opened this issue Apr 10, 2022 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Woodyiiiiiii commented Apr 10, 2022

Binary-search

class Solution {
    public int maximumCandies(int[] candies, long k) {
        
        long sum = 0;
        long ans = 0;
        
        for (int candy : candies) {
            sum += candy;
        }
        if (sum < k) {
            return (int)ans;
        }
        
        long l = 1, r = sum;
        while (l <= r) {
            long mid = l + (r - l) / 2;
            if (check(candies, mid, k)) {
                ans = mid;
                l = mid + 1;
            } else {
                r = mid - 1;
            }
        }
        
        return (int)ans;
        
    }
    
    private boolean check(int[] candies, long limit, long k) {
        for (int candy : candies) {
            if (candy < limit) {
                continue;
            } else {
                k -= candy / limit;
            }
        }
        return k <= 0;
    }
    
}

时隔一年多巩固二分类型题目时再写了这道题:

class Solution {
    public int maximumCandies(int[] candies, long k) {
        long lo = 0, hi = (long) (1e7 + 1);
        while (lo < hi) {
            long mid = (lo + hi) >> 1;
            if (check(candies, k, mid)) {
                lo = mid + 1;
            } else {
                hi = mid;
            }
        }
        return (int) (lo - 1);
    }

    // distribute k children with target number of candies
    private boolean check(int[] candies, long k, long target) {
        long cnt = 0;
        if (target == 0) {
            return true;
        }
        for (int candy : candies) {
            cnt += candy / target;
            if (cnt >= k) {
                return true;
            }
        }
        return cnt >= k;
    }
}

有两个小tips:

  1. cnt变量用long才过了
  2. 发现最近时不时要用/或者%作为数学计算
  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