You are given an integer array demand, where demand[i] is the amount of fuel required by the ith car.
You are also given an integer array fuel of length 2. There are exactly two fuel dispensers, numbered 0 and 1, where fuel[j] is the initial amount of fuel available in dispenser j.
Cars are allowed to start refueling in increasing index order. Car 0 becomes allowed at time 0, and for each i > 0, car i becomes allowed exactly when car i - 1 starts refueling.
The refueling process follows these rules:
demand[i] fuel remaining.demand[i] seconds and reduces the remaining fuel in that dispenser by demand[i].demand[i] fuel remaining, the process terminates and no further cars can be served.The waiting time of a car is the time between when it becomes allowed to start refueling and when it actually starts.
Return the minimum possible value of the maximum waiting time among all served cars over all assignments that maximize the number of served cars. If no car can be served, return -1.
Example 1:
Input: demand = [6,8,4,6,5], fuel = [16,13]
Output: 6
Explanation:
| Car | Becomes allowed at | Starts refueling at | Dispenser used | Remaining fuel before start (dispenser 0, dispenser 1) |
Waiting time |
|---|---|---|---|---|---|
| 0 | 0 | 0 | 1 | (16, 13) | 0 |
| 1 | 0 | 0 | 0 | (16, 7) | 0 |
| 2 | 0 | 6 | 1 | (8, 7) | 6 |
| 3 | 6 | 8 | 0 | (8, 3) | 2 |
Car 4 becomes allowed at time 8, but when both dispensers are free, their remaining fuel is (2, 3), which is less than demand[4] = 5.
Therefore, the process terminates. The maximum waiting time among served cars is 6.
Example 2:
Input: demand = [10,15], fuel = [12,17]
Output: 0
Explanation:
Example 3:
Input: demand = [10,5], fuel = [8,8]
Output: -1
Explanation:
Constraints:
1 <= demand.length <= 501 <= demand[i] <= 20fuel.length == 21 <= fuel[i] <= 50Use dynamic programming over the cars in order. For each dispenser, store its remaining fuel and the time until it becomes free, measured from when the current car becomes allowed.
If the current car is assigned to a dispenser whose remaining busy time is wait, its waiting time is wait. Decrease that dispenser's fuel and set its new busy time to demand[i].
Because the next car becomes allowed when the current car starts, subtract wait from the other dispenser's busy time, stopping at 0.
For every state, first maximize the number of cars that can be served. Among assignments serving that maximum number, minimize the maximum waiting time encountered.
[6,8,4,6,5] [16,13]
[10,15] [12,17]
[10,5] [8,8]