Ad platform~25 min2s · 256 MBtarget O(n log (100 × L)) time, O(1) spaceclassic twin: lc-1891binary-search-answer
An advertising agency hangs banners from sponsor ropes. It has several ropes, each with a length in whole metres. It needs k pieces of rope that all have the same length, to hang k banners at the same height.
Each piece is cut from one rope, and the leftover of a rope is thrown away. The agency wants the pieces as long as possible. The length may be a fraction of a metre, and the cutting machine works in hundredths of a metre.
Write longest_piece(ropes, k).
ropes[i] is the length of the i-th rope in whole metres.r metres is 100 × r hundredths, and it gives floor(100 × r / length) pieces of a given length.k pieces. Return 0 when even a piece of 1 hundredth cannot give k pieces.Input: ropes = [8, 5, 3], k = 5
Output: 266A piece of 2.66 metres gives 3 + 1 + 1 = 5 pieces, because 800, 500 and 300 hundredths divide by 266 to 3, 1 and 1. A piece of 2.67 metres gives only 4. The trace halves the range of lengths and keeps the upper half when the length works.
| lo | hi | Length tested | Pieces | Decision |
|---|---|---|---|---|
| 0 | 800 | 400 | 3 | too few: hi becomes 399 |
| 0 | 399 | 200 | 7 | enough: lo becomes 200 |
| 200 | 399 | 300 | 4 | too few: hi becomes 299 |
| 200 | 299 | 250 | 6 | enough: lo becomes 250 |
| 250 | 299 | 275 | 4 | too few: hi becomes 274 |
| 250 | 274 | 262 | 5 | enough: lo becomes 262 |
| 262 | 274 | 268 | 4 | too few: hi becomes 267 |
| 262 | 267 | 265 | 5 | enough: lo becomes 265 |
| 265 | 267 | 266 | 5 | enough: lo becomes 266 |
| 266 | 267 | 267 | 4 | too few: hi becomes 266 |
Input: ropes = [1], k = 1000
Output: 0A piece of 1 hundredth gives only 100 pieces from a rope of 1 metre, so 1,000 pieces are not possible.
Input: ropes = [4], k = 2
Output: 200Two pieces of 2.00 metres use the whole rope.
1 ≤ ropes.length ≤ 100,0001 ≤ ropes[i] ≤ 1,000,000,000 (metres)1 ≤ k ≤ 1,000,000,000The longest possible piece is 100 × 10^9 = 10^11 hundredths. Trying each length from the top down costs up to 10^11 tests, each over all ropes. A longer piece never gives more pieces, so halving the range needs only about 37 tests, each one pass over the ropes.