-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path1231-divide-chocolate.js
More file actions
55 lines (48 loc) · 1.34 KB
/
1231-divide-chocolate.js
File metadata and controls
55 lines (48 loc) · 1.34 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
47
48
49
50
51
52
53
54
55
/**
* 1231. Divide Chocolate
* https://leetcode.com/problems/divide-chocolate/
* Difficulty: Hard
*
* You have one chocolate bar that consists of some chunks. Each chunk has its own sweetness
* given by the array sweetness.
*
* You want to share the chocolate with your k friends so you start cutting the chocolate bar
* into k + 1 pieces using k cuts, each piece consists of some consecutive chunks.
*
* Being generous, you will eat the piece with the minimum total sweetness and give the other
* pieces to your friends.
*
* Find the maximum total sweetness of the piece you can get by cutting the chocolate bar optimally.
*/
/**
* @param {number[]} sweetness
* @param {number} k
* @return {number}
*/
var maximizeSweetness = function(sweetness, k) {
let left = Math.min(...sweetness);
let right = sweetness.reduce((sum, val) => sum + val, 0);
let result = left;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (canDivide(mid)) {
result = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
function canDivide(minSweetness) {
let pieces = 0;
let currentSum = 0;
for (const chunk of sweetness) {
currentSum += chunk;
if (currentSum >= minSweetness) {
pieces++;
currentSum = 0;
}
}
return pieces >= k + 1;
}
};