Problem 304398 · medium · Level 03 Linear Management & Searching

Earliest Harvest Day

binary search on the answer · greedy

A row of plots is planted; ripe[i] is the day plot i becomes ripe. To fill an order you need bunches bunches, and each bunch must be picked from size adjacent plots that are all ripe. A plot can be used in at most one bunch. Return the earliest day on which the order can be filled, or -1 if it never can.

Examples

Input:  ripe = [4, 9, 2, 6, 3, 8], bunches = 3, size = 1
Output: 4

Input:  ripe = [4, 9, 2, 6, 3, 8], bunches = 2, size = 4
Output: -1
Explanation: six plots can never give two separate groups of four.

Input:  ripe = [2, 4, 12, 3, 1, 4, 2], bunches = 2, size = 3
Output: 12
Explanation: before day 12 the unripe plot splits the row into runs of 2 and 4, which give only one bunch of 3.

Constraints

  • 1 <= len(ripe) <= 5 * 10**4, 1 <= ripe[i] <= 10**9
  • 1 <= bunches, size <= len(ripe)
  • Required time: O(n log(max(ripe))).

Goals

  • Check feasibility with a single pass that tracks runs of adjacent items
  • Detect impossibility before searching
Starting Python…