Skip to content

1891. Cutting Ribbons 👍

  • Time: $O(n\log(\max - \min))$
  • Space: $O(1)$
 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
class Solution {
 public:
  int maxLength(vector<int>& ribbons, int k) {
    int l = 1;
    int r = accumulate(ribbons.begin(), ribbons.end(), 0L) / k + 1;

    while (l < r) {
      const int m = (l + r) / 2;
      if (!isCutPossible(ribbons, m, k))
        r = m;
      else
        l = m + 1;
    }

    return l - 1;
  }

 private:
  bool isCutPossible(const vector<int>& ribbons, int length, int k) {
    int count = 0;
    for (const int ribbon : ribbons)
      count += ribbon / length;
    return count >= k;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int maxLength(int[] ribbons, int k) {
    int l = 1;
    int r = (int) (Arrays.stream(ribbons).asLongStream().sum() / k) + 1;

    while (l < r) {
      final int m = (l + r) / 2;
      if (!isCutPossible(ribbons, m, k))
        r = m;
      else
        l = m + 1;
    }

    return l - 1;
  }

  private boolean isCutPossible(int[] ribbons, int length, int k) {
    int count = 0;
    for (final int ribbon : ribbons)
      count += ribbon / length;
    return count >= k;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def maxLength(self, ribbons: list[int], k: int) -> int:
    def isCutPossible(length: int) -> bool:
      count = 0
      for ribbon in ribbons:
        count += ribbon // length
      return count >= k

    l = 1
    r = sum(ribbons) // k + 1

    while l < r:
      m = (l + r) // 2
      if not isCutPossible(m):
        r = m
      else:
        l = m + 1

    return l - 1