-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2305-fair-distribution-of-cookies.js
More file actions
46 lines (40 loc) · 1.23 KB
/
2305-fair-distribution-of-cookies.js
File metadata and controls
46 lines (40 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* 2305. Fair Distribution of Cookies
* https://leetcode.com/problems/fair-distribution-of-cookies/
* Difficulty: Medium
*
* 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 maximum total cookies obtained by a single
* child in the distribution.
*
* Return the minimum unfairness of all distributions.
*/
/**
* @param {number[]} cookies
* @param {number} k
* @return {number}
*/
var distributeCookies = function(cookies, k) {
const distribution = new Array(k).fill(0);
let result = Infinity;
distribute(0);
return result;
function distribute(index) {
if (index === cookies.length) {
result = Math.min(result, Math.max(...distribution));
return;
}
for (let i = 0; i < k; i++) {
distribution[i] += cookies[index];
if (distribution[i] < result) {
distribute(index + 1);
}
distribution[i] -= cookies[index];
if (distribution[i] === 0) break;
}
}
};