-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1231.divide-chocolate.java
58 lines (50 loc) · 2.14 KB
/
1231.divide-chocolate.java
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
56
57
58
/*
* @lc app=leetcode id=1231 lang=java
*
* [1231] Divide Chocolate
*/
// @lc code=start
class Solution {
// 1. find the min and sum/k+1 (left & right) in sweetness
// 2. binary search between left & right,
// and Check if we can cut the chocolate into k + 1 pieces
// with sweetness no less than mid
// 3. ouput the right, which is the optimal answer.
public int maximizeSweetness(int[] sweetness, int k) {
// Initialize the left and right boundaries.
// left = 1 and right = total sweetness / number of people.
int numberOfPeople = k + 1;
int left = Arrays.stream(sweetness).min().getAsInt();
int right = Arrays.stream(sweetness).sum() / numberOfPeople;
while (left < right) {
// Get the middle index between left and right boundary indexes.
// cur_sweetness stands for the total sweetness for the current person.
// people_with_chocolate stands for the number of people that have
// a piece of chocolate of sweetness greater than or equal to mid.
int mid = (left + right + 1) / 2;
int curSweetness = 0;
int peopleWithChocolate = 0;
// Start assigning chunks to the current people,.
for (int s : sweetness) {
curSweetness += s;
// If the total sweetness for him is no less than mid, meaning we
// have done with him and should move on to assigning chunks to the next people.
if (curSweetness >= mid) {
peopleWithChocolate += 1;
curSweetness = 0;
}
}
// Check if we successfully give everyone a piece of chocolate with sweetness
// no less than mid, and eliminate the search space by half.
if (peopleWithChocolate >= numberOfPeople) {
left = mid;
} else {
right = mid - 1;
}
}
// Once the left and right boundaries coincide, we find the target value,
// that is, the maximum possible sweetness we can get.
return right;
}
}
// @lc code=end