Binary Search, C++ With Explanation ✅✅
\n# Approach\n Describe your approach to solving the problem. \nHere i apply Binary Search Algorithm to find out Maximum Number of candies.\n\nMaximum Number of
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere i apply **Binary Search Algorithm** to find out Maximum Number of candies.\n\nMaximum Number of Candies Always Belong to range **[1 , Maximum of array]** , number of Maximum Candies can be any Element from this sorted array that satisfy the given condition-\n**[1,2,3,4,5,6,7,8,9...........Maximum of given array]**\n\nFirst  = 1 \nLast   = Maximum\n\nFind Index That Satisfy the Given Condition(allocate piles of candies to k children such that each child gets the same number of candies) ?\n\n**Note:-Here I also apply the same approach, have a look at these problems and try to solve with the same approach.**\n\n**Problem:-** https://leetcode.com/problems/koko-eating-bananas/description/\n**Solution:-** https://leetcode.com/problems/koko-eating-bananas/solutions/3601174/binary-search-c-with-explanation/\n\n\n\n\n# Complexity\n- Time complexity:O(N*Log(N))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    bool check(vector<int> arr,long long k,int n)\n    {\n        long long count = 0;\n        for(int i = 0;i<arr.size();i++)\n        count+=(arr[i]/n);\n        \n        if(count>=k)\n        return true;\n\n        return false;\n    }\n    int maximumCandies(vector<int>& arr, long long k) {\n        \n           int n = arr.size(),ans = 0;\n           int first = 1,last = INT_MIN;\n\n           for(int i = 0;i<n;i++)\n           last = max(last,arr[i])+1;\n        \n           while(first<last)\n           {\n               int mid = (first+last)/2;\n\n               if(check(arr,k,mid))\n               {\n                   first = mid+1;\n                   ans = max(ans,mid);\n               }\n               else\n               last = mid;\n           }\n           \n           return ans;\n    }\n};\n```\n![upvote.jpg](https://assets.leetcode.com/users/images/4d957791-93e7-424e-a2ba-a546017c5145_1685983637.253224.jpeg)\n
['Binary Search', 'C++']