progress

~/problems / Binary search / Binary search on the answer

Biggest square cookies

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~20 min

A bakery cuts square cookies of whole-number side s from shortbread sheets (w, h); one sheet yields (w // s) * (h // s) cookies, and leftovers are thrown away.

Write biggest_side(sheets: list[tuple[int, int]], need: int) -> int that returns the largest s for which all sheets together yield at least need cookies, or 0 if even s = 1 falls short.

biggest_side([(10, 7), (4, 4)], 5)    # 3   (s = 3 gives 3*2 + 1*1 = 7 cookies; s = 4 gives only 3)
Two shortbread sheets, 10 by 7 and 4 by 4, cut into 3 by 3 cookies: six fit on the large sheet and one on the small sheet, 7 in total, and the leftover strips are thrown away
biggest_side([(10, 7), (4, 4)], 3)    # 4
biggest_side([(2, 3)], 7)             # 0   (only 6 unit squares exist)

Up to 10^4 sheets, sides up to 10^9, need up to 10^18. In C++/Java, stop adding once you reach need, or the count overflows. ⭐ Bonus: a speed test with huge sheets earns a star for binary search.

Show hint

the count only drops as s grows. Binary search for the last s that still works.

Topic: Binary search on the answer. Monotonic feasibility check + search the smallest value that works.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc