KatInterview

Longest Streak of Growing Daily Distinct Picks

Greedy & IntervalsAuto-graded · 24 test cases
MediumAuto-gradedGreedy & Intervalsgreedybinary-searchprefix-sums

Last updated

Find how many days a growing-size distinct-item picking schedule can run, using binary search on the answer plus a capacity feasibility check.

A warehouse holds several bins. Bin j starts with stock[j] items.

Every day you must take items according to a schedule that grows by one each day:

  • On day 1 you take one item from exactly 1 bin.
  • On day 2 you take one item from each of exactly 2 different bins.
  • On day k you take one item from each of exactly k different bins.

A bin can be used at most once on a given day, and it can never be taken from once it is empty. Bins may be chosen freely each day, so the same bin can be used on many different days as long as it still has items.

You may stop at any point, but you cannot skip days or do a smaller pick than required. Return the largest D such that days 1, 2, ..., D can all be carried out in order.

If no bins exist, return 0.

Constraints

  • 0 <= len(stock) <= 2 * 10^5
  • 1 <= stock[j] <= 10^9
  • The answer is never larger than len(stock), since day k needs k different bins.
  • Your solution should run in roughly O(n log n) time.

Examples

Example 1

Input: max_days_distinct_picks([1, 2, 3])

Output: 3

Example 2

Input: max_days_distinct_picks([2, 2, 2])

Output: 3

Example 3

Input: max_days_distinct_picks([3, 3, 1, 1])

Output: 3

Example 4

Input: max_days_distinct_picks([1, 1, 1, 1, 1])

Output: 2

Hints

Hint 1

If you can finish D days, you can certainly finish D - 1 days. What does that let you do with the search for the answer?

Hint 2

For a fixed D, consider any t of the days. A bin can serve at most min(stock[j], t) of them. Compare that total supply with the demand of the t hardest days (the t largest picks).

Hint 3

The sum of min(stock[j], t) over all bins is quick to compute with a sorted copy and prefix sums, since bins with stock below t contribute their full stock and the rest contribute t. Check every t from 1 to D.