KatInterview

Maximize Uniform Cut Length for Target Segment Count

Heaps, Sorting & SearchAuto-graded · 25 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searcharraysgreedy

Last updated

Find the maximum integer segment length that can produce at least a specified count of equal-sized pieces using binary search on answer.

You are given a list of positive integers a representing the initial lengths of several materials, and a target integer k representing the minimum number of identical segments required.

Your task is to cut the materials into segments of a fixed integer length $L$. Each original material piece can be cut into zero or more segments of length $L$. Any remainder less than $L$ is discarded, and pieces cannot be joined together.

Determine the maximum possible integer length $L \ge 1$ such that the total count of segments of length $L$ produced across all materials is at least $k$.

If k <= 0, return the maximum value present in a (or 0 if a is empty). If it is impossible to obtain at least k segments of length $L \ge 1$, return 0.

Constraints

  • 0 <= len(a) <= 10^5
  • 1 <= a[i] <= 10^9 for each element in a
  • -10^9 <= k <= 10^9

Examples

Example 1

Input: max_wood_length([5, 9, 7], 5)

Output: 3

Example 2

Input: max_wood_length([5, 9, 7], 20)

Output: 1

Example 3

Input: max_wood_length([4, 4, 4], 3)

Output: 4

Hints

Hint 1

Notice that if a segment length $L$ yields at least $k$ pieces, any smaller length $L' < L$ will yield at least as many pieces.

Hint 2

The maximum plausible length is `max(a)`. This allows binary searching for $L$ in the range `[1, max(a)]`.

Hint 3

For a candidate length `mid`, compute the total segments as `sum(x // mid for x in a)`. If this sum is at least $k$, try larger values of `mid`.