Closest Vehicle and Charger in a Line
Problem statement
A line of cells is given as an array cells. Each value means:
0: an empty cell1: a vehicle2: a charger
The distance between two cells is the absolute difference of their indices. Return the smallest distance between any vehicle and any charger. If the line has no vehicle or no charger, return -1.
Function
closestVehicleChargerDistance(cells: int[]) → intExamples
Example 1
cells = [0,1,0,0,2,0,1]return = 2The vehicles are at indices 1 and 6, and the charger is at index 4. The distances are 3 and 2, so the answer is 2, from the vehicle at index 6.
Example 2
cells = [2,1]return = 1The charger at index 0 and the vehicle at index 1 are next to each other.
Example 3
cells = [1,0,1]return = -1The line has vehicles but no charger, so the answer is -1.
Constraints
1 <= cells.length <= 10^50 <= cells[i] <= 2