Maximum Candies Allocated to K Children - Binary Search [JS]

Description 

Solution: Binary Search

Binary search for the maximum amount of candies.
How to check whether a certain amount is enough for at least k piles:
Since we can't join piles together, the amount of piles we can get from each candies[i] is Math.floor(candies[i] / amount)
If the sum of allMath.floor(candies[i] / amount)>= k, the amount is enough.

n = length of candiesm = max(candies)
Time Complexity: O(n log(m))
Space Complexity: O(1)

var maximumCandies = function(candies, k) {
  let low = 0, high = Math.max(...candies);
  while (low < high) {
    let mid = Math.ceil((low + high) / 2);
    if (isEnough(mid)) low = mid;
    else high = mid - 1;
  }
  return low;
  
  function isEnough(amount) {
    let count = 0;
    for (let i = 0; i < candies.length; i++) {
      count += Math.floor(candies[i] / amount);
    }
    return count >= k;
  }
};

javascript

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]