Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

The largest equal share for k people

Medium · Target 20 minutes · Binary search · Type asked atAmazonGoldman Sachs

You have piles of sweets, piles[i] in pile i. You may split any pile into smaller piles, but you may not merge piles. Give each of k children exactly one pile, all of the same size x; some sweets may be left over. Return the largest possible x, or 0 if every child cannot get even one sweet.

Examples

InputOutputWhy
piles = [5, 8, 6], k = 35Shares of 5: one from each pile. Shares of 6 give only two.
piles = [2, 5], k = 110There are only 7 sweets.
piles = [4, 7, 5], k = 431 + 2 + 1 = 4 shares of 3.

Constraints

  • 1 ≤ piles.length ≤ 10⁵
  • 1 ≤ piles[i] ≤ 10⁷
  • 1 ≤ k ≤ 10¹²

Hints

Hint 1

For a share size x, how many shares can pile i provide?

Hint 2

⌊piles[i] / x⌋, because shares cannot combine sweets from two piles. Sum over the piles.

Hint 3

Larger x never gives more shares, so "at least k shares" holds up to some x and fails after it. Search for the last x that holds; if even x = 1 fails, the answer is 0.

Where people lose marks

  • Dividing by zero when the search reaches x = 0: treat 0 as feasible without computing shares(0).
  • Holding k or the share count in 32 bits: k reaches 10¹².
  • Returning 1 when the total is smaller than k.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.