Fewest Orders to Hit the Goal

Medium · Sliding Window · about 20 min

A bakery lists its orders for the day in time order: orders[i] is the value of order i (every value is a positive whole number). The manager wants the shortest run of back-to-back orders whose total is at least goal.

Return the length of that run, or 0 if no run reaches the goal. goal is at least 1.

Examples:

shortest_order_run([2, 3, 1, 2, 4, 3], 7) → 2 (4 + 3)

shortest_order_run([1, 1, 1, 1, 1], 11) → 0

Aim for O(n).

Hints

  • All orders are positive, so a longer run always has a bigger total.
  • Add orders on the right until the total reaches the goal.
  • Then keep removing orders from the left while the total still reaches the goal, recording the length each time.

Learn the pattern first: the Sliding Window lesson.

More Sliding Window problems