Minimum Integer Speed to Cross All Segments Before a Deadline

Implement minSpeedToArrive

A route is made of segments — dist[i] distance units each, traveled in order at a single constant integer speed. Every segment except the last one may only be started at the top of an hour (so even finishing a segment slightly early still means waiting until the next full hour to begin the next one); the final segment has no such restriction and can end at any exact moment. Given a deadline in minutes, deadlineMinutes, find the minimum integer speed that completes the whole route in time, or -1 if no integer speed manages it. Every non-final segment effectively costs ⌈dist[i] / speed⌉ whole hours because of the hour-boundary rule, while the final segment costs exactly dist[last] / speed hours — computed here through cross-multiplication rather than division, so every comparison stays in exact integers with no fractional or floating-point arithmetic at all. Total travel time only ever decreases (or stays flat) as speed increases, which makes this a binary search on the answerBinary Search on the AnswerInstead of searching a sorted array, the search runs directly over the space of possible answers (here, every candidate integer speed). It works whenever "is this candidate good enough?" is monotonic — once a candidate works, every faster candidate keeps working too. — search directly over candidate speeds rather than trying to reason about the schedule algebraically.

Example 1:

Input: dist = [2,5,4], deadlineMinutes = 400

Output: 2

Example 2:

Input: dist = [2,5,4], deadlineMinutes = 360

Output: 2

Example 3:

Input: dist = [2,5,4], deadlineMinutes = 260

Output: 3

+ 5 hidden test cases run on Submit.

Constraints:

  • 1 ≤ number of segments ≤ 100
  • 1 ≤ dist[i] ≤ 1000
  • 1 ≤ deadlineMinutes ≤ 10⁴

dist =

[2, 5, 4]

deadlineMinutes =

400