LeetCode 1231. Divide Chocolate

Problem Statement

Binary Search


impl Solution {
pub fn maximize_sweetness(sweetness: Vec<i32>, k: i32) -> i32 {
let mut l = sweetness.clone().into_iter().fold(None, |min, x| match min {
None => Some(x),
Some(y) => Some(if x < y { x } else { y }),
}).unwrap();
let mut r = sweetness.clone().iter().fold(0, |mut r, &val| {r += val; r});
while l < r {
let (mid, mut sum, mut cut) = ((l + r + 1) / 2, 0, 0);
for val in sweetness.clone() {
sum += val;
if sum >= mid {
sum = 0; cut += 1;
if cut > k {
break;
}
}
}
if cut > k {
l = mid;
} else {
r = mid - 1;
}
}

return l;
}
}