You are given an integer array cookies, where cookies[i] denotes the number of cookies in the ith bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to.
All the cookies in the same bag must go to the same child and cannot be split up.
The unfairness of a distribution is defined as the maximumtotal cookies obtained by a single child in the distribution.
Return theminimum unfairness of all distributions.
Input: cookies =[8,15,10,20,8], k =2Output: 31Explanation: One optimal distribution is[8,15,8] and [10,20]- The 1st child receives [8,15,8] which has a total of 8+15+8=31 cookies.- The 2nd child receives [10,20] which has a total of 10+20=30 cookies.The unfairness of the distribution ismax(31,30)=31.It can be shown that there is no distribution with an unfairness less than 31.
Input: cookies =[6,1,3,2,2,4,1,2], k =3Output: 7Explanation: One optimal distribution is[6,1],[3,2,2], and [4,1,2]- The 1st child receives [6,1] which has a total of 6+1=7 cookies.- The 2nd child receives [3,2,2] which has a total of 3+2+2=7 cookies.- The 3rd child receives [4,1,2] which has a total of 4+1+2=7 cookies.The unfairness of the distribution ismax(7,7,7)=7.It can be shown that there is no distribution with an unfairness less than 7.
Since the number of bags is small (≤8), we can try all possible ways to distribute the bags among the children. For each distribution, we track the maximum cookies any child gets (unfairness) and try to minimize it.
classSolution {
int ans = Integer.MAX_VALUE;
publicintdistributeCookies(int[] cookies, int k) {
int[] dist =newint[k];
dfs(cookies, 0, dist, k);
return ans;
}
voiddfs(int[] cookies, int i, int[] dist, int k) {
if (i == cookies.length) {
int max = 0;
for (int d : dist) max = Math.max(max, d);
ans = Math.min(ans, max);
return;
}
for (int j = 0; j < k; ++j) {
dist[j]+= cookies[i];
if (dist[j]< ans) dfs(cookies, i+1, dist, k);
dist[j]-= cookies[i];
if (dist[j]== 0) break;
}
}
}
classSolution {
var ans = Int.MAX_VALUE
fundistributeCookies(cookies: IntArray, k: Int): Int {
val dist = IntArray(k)
fundfs(i: Int) {
if (i == cookies.size) {
ans = minOf(ans, dist.maxOrNull()!!)
return }
for (j in0 until k) {
dist[j] += cookies[i]
if (dist[j] < ans) dfs(i + 1)
dist[j] -= cookies[i]
if (dist[j] ==0) break }
}
dfs(0)
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
defdistributeCookies(self, cookies: list[int], k: int) -> int:
ans = float('inf')
dist = [0] * k
defdfs(i: int) ->None:
nonlocal ans
if i == len(cookies):
ans = min(ans, max(dist))
returnfor j in range(k):
dist[j] += cookies[i]
if dist[j] < ans:
dfs(i +1)
dist[j] -= cookies[i]
if dist[j] ==0:
break dfs(0)
return ans
⏰ Time complexity: O(k^n), where n is the number of bags and k is the number of children. Each bag can go to any child, so all assignments are tried. Pruning helps but does not change the worst case.
🧺 Space complexity: O(n + k), for the recursion stack and the distribution array.