← Questions

Fuel station queue with three dispensers

0
TeslaCoding

A fuel station has three dispensers named X, Y and Z. Each starts with a known number of liters. A queue of cars waits at the station, and all of them are in line at time 0. Car i needs demands[i] liters.

Rules:

  • Only the car at the front of the queue chooses a dispenser. Cars never overtake one another.
  • The car may use a dispenser only if it is free (not serving a car) and holds at least the car's demand.
  • If several dispensers qualify, the car takes the first by name: X, then Y, then Z.
  • If none qualifies right now, the car waits at the front and blocks everyone behind it.
  • Fuel flows at 1 liter per second, so a car with demand d keeps its dispenser busy for d seconds. A dispenser that finishes at time t can serve the next car at time t.

A car's waiting time is the time it starts refuelling. Implement:

def max_wait(demands: list[int], x: int, y: int, z: int) -> int

Return the longest waiting time over all cars. Return -1 if some car can never refuel.

Constraints: 0 <= len(demands) <= 10^5; 0 <= demands[i], x, y, z <= 10^9.

Example 1: demands = [3, 5, 4, 2], x = 10, y = 5, z = 1 returns 7.

  • At 0, car 1 takes X (7 liters left, busy until 3). Car 2 takes Y (0 left, busy until 5).
  • Car 3 needs 4 liters. Only X has enough, so it waits and starts at 3 (3 left, busy until 7).
  • Car 4 needs 2 liters. Only X has enough, so it starts at 7.

Example 2: demands = [5, 1], x = 5, y = 0, z = 0 returns -1. Car 1 empties X, and no dispenser has fuel for car 2.

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding