DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Maximum Candies Allocated to K Children

Problem

//same as coco eating bananas,  //capacity to ship packages within d days //aggresive cows class Solution { public int maximumCandies(int[] candies, long k) { long sum = 0; int max = 0; for(int i : candies){ sum+=i; max = Math.max(max, i);//max no. of candy that can be allocated to child from the same lot } if(sum<k) return 0; int low =1;// lowest no. of candy that can be allocated to child from the same lot int high = max; while(low<=high){ int mid = (low+high)/2; if(is(candies,k,mid)){ low = mid+1; } else high = mid-1; } return high; } public boolean is(int arr[], long k,int target){ long children = 0; for(int i : arr){ if(i >= target){ // if the candy lot size is greater that current target(max candy allocation value from the same lot) children+=i/target;// then we can get assign i/target no. of children the same no. of candies } } return children>=k;// if the no. of children is greater than the k (childrens) then target is one of the valid candy lot size } } 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)