[LeetCode] Cutting Ribbons

1891. Cutting Ribbons

You are given an integer array ribbons, where ribbons[i] represents the length of the ith ribbon, and an integer k. You may cut any of the ribbons into any number of segments of positive integer lengths, or perform no cuts at all.

  • For example, if you have a ribbon of length 4, you can:
  • Keep the ribbon of length 4,
  • Cut it into one ribbon of length 3 and one ribbon of length 1,
  • Cut it into two ribbons of length 2,
  • Cut it into one ribbon of length 2 and two ribbons of length 1, or
  • Cut it into four ribbons of length 1.

Your goal is to obtain k ribbons of all the same positive integer length. You are allowed to throw away any excess ribbon as a result of cutting.

Return the maximum possible positive integer length that you can obtain k ribbons of, or 0 if you cannot obtain k ribbons of the same length.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int maxLength(vector<int>& ribbons, int k) {
long long l = 1, r = INT_MAX, res = 0;
while(l <= r) {
long long m = l + (r-l)/2, cut = 0;
for(auto& r : ribbons) cut += r / m;

if(cut >= k) {
res = max(res, m);
l = m + 1;
} else {
r = m - 1;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/06/PS/LeetCode/cutting-ribbons/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.