Python | Simple Binary Search | O(n log m), O(1) | Beats 100%
CodeComplexity

Time complexity: O(log(m)∗n). The binary search has initial range from 0 to m where m is average of total candies, time is log(m). isValidSize()
# Code
```python3 []
class Solution:
    def maximumCandies(self, candies: List[int], k: int) -> int:
        def isValidSize(group_candies):
            groups = 0
            for candy in candies:
                groups += candy // group_candies # add groups that can be made from candy
            return groups >= k

        left, right = 0, sum(candies) // k # min is 0 candy per group, max is split all candies evenly

        while left < right: # binary search to find max number of candies per group
            mid = 1 + (left + right) // 2 # 1 + or ceil( / 2) to avoid looping with left = mid
            
            if isValidSize(mid): # true if can make k groups of mid size
                left = mid # valid group, move left up and check higher group sizes
            else:
                right = mid - 1 # invalid group, move right down and check lower group sizes
        
        return left # left = right = max valid size. right + 1 is first invalid size
```

# Complexity
- Time complexity: $$O(log(m)*n)$$. The binary search has initial range from 0 to m where m is average of total candies, time is log(m). isValidSize() checks n candies and performs constant operations to find how many groups can be made for a given size, time is n. Each iteration of the binary search calls isValidSize(), so overall time is log(m) * n.

- Space complexity: $$O(1)$$. Only uses constant space variables.

# Performance

![Screenshot (13).png](https://assets.leetcode.com/users/images/ebbe4b38-c391-420d-a493-8b19b43e10a6_1741915913.5581305.png)

['Binary Search', 'Python3']