LeetCode 1891: Cutting Ribbons Solution

Master LeetCode problem 1891 (Cutting Ribbons), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1891. Cutting Ribbons

Problem Explanation

Explanation:

To solve this problem, we can use binary search to find the maximum possible length of the ribbon that can be cut into k pieces. We can start by setting the minimum possible length to 1 and the maximum possible length to the maximum ribbon length in the input array. Then, we perform binary search within this range to find the maximum valid length that can be cut into k pieces. :

Solution Code

class Solution {
    public int maxLength(int[] ribbons, int k) {
        int left = 1;
        int right = Arrays.stream(ribbons).max().getAsInt();
        
        while (left < right) {
            int mid = left + (right - left + 1) / 2;
            if (isValid(ribbons, k, mid)) {
                left = mid;
            } else {
                right = mid - 1;
            }
        }
        
        return left;
    }
    
    private boolean isValid(int[] ribbons, int k, int length) {
        int count = 0;
        
        for (int ribbon : ribbons) {
            count += ribbon / length;
        }
        
        return count >= k;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1891 (Cutting Ribbons)?

This page provides optimized solutions for LeetCode problem 1891 (Cutting Ribbons) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1891 (Cutting Ribbons)?

The time complexity for LeetCode 1891 (Cutting Ribbons) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1891 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1891 in Java, C++, or Python.

Back to LeetCode Solutions