KatInterview

Minimum Largest Piece After K Cuts on a Log

Heaps, Sorting & SearchAuto-graded · 17 test cases
EasyAuto-gradedHeaps, Sorting & Searchbinary searchgreedysorting

Last updated

Tests binary search on the answer to find the minimum possible largest piece when splitting a log into at least K+1 pieces.

Minimum Largest Piece After K Cuts on a Log

You are given a log of length n (in centimetres). You must make exactly k cuts, each cut positioned at an integer centimetre mark strictly inside the log (i.e. at positions 1, 2, …, n-1). Each cut is independent — you may cut wherever you like.

After all k cuts the log is divided into k+1 pieces. Your goal is to minimise the length of the largest piece.

Return the minimum possible length of the largest piece.

Constraints

  • 1 ≤ n ≤ 10^9
  • 1 ≤ k ≤ min(n - 1, 2000)
  • All cuts must land at distinct integer positions strictly inside [1, n-1].
  • It is always possible to make k cuts (guaranteed by the constraints above).

Examples

Example 1

Input: min_largest_piece(10, 2)

Output: 4

Example 2

Input: min_largest_piece(7, 3)

Output: 2

Example 3

Input: min_largest_piece(1000000000, 1)

Output: 500000000

Hints

Hint 1

Think about binary searching on the answer: for a fixed maximum piece length L, can you always place k cuts to ensure no piece exceeds L?

Hint 2

For a given candidate maximum length L, the minimum number of cuts needed is ceil(n / L) - 1. Check whether this is ≤ k.

Hint 3

The answer lies in the range [ceil(n / (k+1)), n]. Binary search for the smallest L where ceil(n / L) - 1 ≤ k.