✅ 100% 🧊 10 ms | Binary Search & optimizations
Please Upvote 🔝 Appreciations!CodeComplexity
Time complexity: O( n log n )
Space complexity: O( 1 )
# Please Upvote 🔝 Appreciations!
![image.png](https://assets.leetcode.com/users/images/7c3830ed-e09a-4d72-9f65-945ac5a00895_1741946098.795267.png)
# Code
``` kotlin []
class Solution {
    fun maximumCandies(candies: IntArray, k: Long): Int {
        var right = (candies.sumOf { it.toLong() } / k).toInt()
        var left = 0  

        while (left < right) {
            val curr: Int = (left + right + 1) / 2
            var count: Long = 0L
            for (pile in candies) {
                count += pile / curr
                if (count >= k) break  
            }
            if (count >= k) left = curr
            else right = curr - 1
        }
        return left
    }
}
```
``` kotlin []
class Solution {
    fun maximumCandies(candies: IntArray, k: Long): Int {
        var right: Int = (candies.sumOf { it.toLong() } / k).toInt()
        var left = 0
        
        while (right > 0) {
            val curr = (left + right + 1) / 2
            var count: Long = 0
            for (pile: Int in candies) {
                if (pile >= curr) count += pile / curr
                if (count >= k) { left = curr; break }
            }
            if (count < k) right = curr - 1
            if (left == right) break
        }
        return right
    }
}
```

# Complexity
- Time complexity: **O(** n log n **)**
- Space complexity: **O(** 1 **)**
['Array', 'Math', 'Binary Search', 'Java', 'Kotlin']