Java | Binary Search | Easy To Understand
Here I am discussing my approach to this problem\nApproach:\n1. First calculate total number of candies. Let it be sum.\n2. If sum < k, return 0 we have more ch
**Here I am discussing my approach to this problem**\n**Approach:**\n1. First calculate **total number** of candies. Let it be `sum`.\n2. If `sum < k`, **return 0** we have **more children than candies**.\n3. If `sum = k`, **return 1** as we have** as many children as candies**.\n4. Else, perform **binary search** on **number of candies** in the range where `low = 1`, and `high = max of candies`.\n5. Check for `mid`, if we can distribute mid number of candies to each children, then we can move `low to mid + 1`, else move` high to mid - 1.`\n6. Store the **last satisfied mid value in `ans`**.\n7. Return `ans`.\n\n**Source Code:**\n```\nclass Solution {\n    public int maximumCandies(int[] candies, long k) {\n        long sum = 0;\n        long max = 0;\n        \n        for(int v : candies) {\n            sum += v;\n            max = Math.max(v, max);\n        }\n        \n        if(sum < k)\n            return 0;\n        \n        if(sum == k)\n            return 1;\n        \n        long x = 1, y = max, ans = 1;\n        \n        while(x <= y) {\n            long mid = (x + y) >> 1;\n            long cur = 0;\n            \n            for(int v : candies) {\n                cur += v / mid;\n            }\n            \n            if(cur>= k) {\n                ans = mid;\n                x = mid + 1;\n            }\n            else\n                y = mid - 1;\n        }\n        \n        return (int) (ans);\n        \n    }\n}\n```\n\n**Complexity Analysis:**\n```\nTime Complexity: O(n * log(max)) // n = number of candy piles, max = max value of candy pile\nSpace Complexity : O(1)\n```
['Binary Tree', 'Java']