A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance between the given start and destination
stops.
The shortest distance between two stops on a circular route is the minimum of the clockwise and counterclockwise distances. We can use prefix sums to quickly compute the distance in either direction.
classSolution {
publicintdistanceBetweenBusStops(int[] distance, int start, int destination) {
if (start > destination) {
int tmp = start; start = destination; destination = tmp;
}
int clockwise = 0, total = 0;
for (int i = 0; i < distance.length; ++i) {
total += distance[i];
if (i >= start && i < destination) clockwise += distance[i];
}
return Math.min(clockwise, total - clockwise);
}
}
1
2
3
4
5
6
7
classSolution:
defdistanceBetweenBusStops(self, distance: list[int], start: int, destination: int) -> int:
if start > destination:
start, destination = destination, start
clockwise = sum(distance[start:destination])
total = sum(distance)
return min(clockwise, total - clockwise)