
You are given a 0-indexed integer array candies. Each element in the array denotes a pile of candies of size candies[i]. You can divide each pile into any number of sub piles, but you cannot merge two piles together.
You are also given an integer k. You should allocate piles of candies to k children such that each child gets the same number of candies. Each child can be allocated candies from only one pile of candies and some piles of candies may go unused.
Return the maximum number of candies each child can get.
1 <= candies.length <= 1051 <= candies[i] <= 1071 <= k <= 1012public static int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2; // 중간값 계산
if (arr[mid] == target) {
return mid; // 찾으면 인덱스 반환
} else if (arr[mid] < target) {
left = mid + 1; // 오른쪽 탐색
} else {
right = mid - 1; // 왼쪽 탐색
}
}
return -1; // 찾지 못함
}
파라미터의 크기가 작은 경우에는 문제가 없었지만, 초기에 활용한 선형탐색은 파라미터의 크기가 커질수록 연산 시간이 크게 증가해 runtime error가 뜨는 경우가 발생.
checkAllocation()의 리턴을 초기에 int로 설정해, long k와 비교하는 연산을 구현했으나, 리턴이 int의 범위를 넘어서는 경우, k와의 유의미한 비교 연산이 불가능해짐.
class Solution {
public int maximumCandies(int[] candies, long k) {
long maxChildren = 0;
// 가장 큰 pile 찾기
int maxPile = 0;
for (int pile: candies)
if (maxPile < pile)
maxPile = pile;
// 이진 탐색을 위한 인덱스
int left = 0;
int right = maxPile;
// 사탕 개수에 대한 이진 탐색
while (left < right) {
int middle = (left + right + 1) / 2;
maxChildren = checkAllocation(candies, middle);
if (maxChildren >= k) {
left = middle;
} else {
right = middle - 1;
}
}
return left;
}
// middle개의 사탕을 받을 수 있는 아이들의 수
public long checkAllocation(int[] candies , int maxCandies) {
long maxChildren = 0;
for (int pile: candies) {
maxChildren += pile / maxCandies;
}
return maxChildren;
}
}