Minimum Speed to Arrive on Time

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute, you must take n trains in sequential order. You are also given an integer array dist, where dist[i] describes the distance of the i-th train ride.

Each train can only depart at an integer hour, so you may need to wait between trains. The last train has no such restriction.

Return the minimum positive integer speed (in km/hr) that all trains must travel at for you to reach the office on time, or -1 if it is impossible.

Examples

Example 1:

Input: dist = [1, 3, 2], hour = 6

Output: 1

Explanation: At speed 1: train 1 takes 1 hr, train 2 takes 3 hrs, train 3 takes 2 hrs = 6 total.

Example 2:

Input: dist = [1, 3, 2], hour = 2.7

Output: 3

Explanation: At speed 3: ceil(1/3)=1 + ceil(3/3)=1 + 2/3 = 2.67 ≤ 2.7.

Example 3:

Input: dist = [1, 3, 2], hour = 1.9

Output: -1

Explanation: Impossible — need at least 2 integer hours for first 2 trains.

Constraints

  • 1 <= dist.length <= 10^5
  • 1 <= dist[i] <= 10^5
  • 1 <= hour <= 10^9
  • There will be at most two digits after the decimal point in hour
Source: Modified Binary Search pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle