FastPrepCut Ribbons to Maximize Equal Length

Cut Ribbons to Maximize Equal Length

Google logoGoogle● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

You are given an array ribbons, where ribbons[i] is the positive integer length of one ribbon, and a positive integer k.

You may cut each ribbon into any number of integer-length pieces. Pieces from different ribbons cannot be joined. Return the greatest integer length length for which the ribbons can produce at least k pieces of exactly that length.

The input guarantees that at least k pieces of length 1 can be produced.

Follow-up

How would the stopping condition and return value change if ribbon lengths and the requested answer could be fractional?

Function

maxLength(ribbons: int[], k: int) → int

Examples

Example 1

ribbons = [9,7,5]k = 3return = 5

Lengths 5, 5, and 5 can be cut from the three ribbons. Length 6 yields only two pieces.

Example 2

ribbons = [7,5,9]k = 4return = 4

The ribbons produce 1 + 1 + 2 = 4 pieces of length 4. A length of 5 produces only three pieces.

Example 3

ribbons = [4,4,4]k = 6return = 2

Each ribbon contributes two pieces of length 2.

Constraints

  • ribbons is non-empty.
  • Every ribbon length is a positive integer.
  • k is positive and does not exceed the total number of unit-length pieces.
  • The total number of pieces is accumulated with a signed 64-bit integer.

More Google problems

See Google hiring insights
public int maxLength(int[] ribbons, int k) {
    // Write your code here.
}
ribbons[9,7,5]
k3
expected5
Checking account…