Sum the clockwise segment between the ordered stops and compare it with the total route distance minus that segment.
Complexity
O(n) time and O(1) space.
Find the shorter travel distance between two stops on a circular route.
Sum the clockwise segment between the ordered stops and compare it with the total route distance minus that segment.
O(n) time and O(1) space.
package main
func distanceBetweenBusStops(distance []int, start int, destination int) int {
if start > destination {
start, destination = destination, start
}
total, direct := 0, 0
for stop, value := range distance {
total += value
if stop >= start && stop < destination {
direct += value
}
}
if direct < total-direct {
return direct
}
return total - direct
}
class Solution:
def distanceBetweenBusStops(self, distance: list[int], start: int, destination: int) -> int:
if start > destination: start, destination = destination, start
direct = sum(distance[start:destination]); return min(direct, sum(distance) - direct)
function distanceBetweenBusStops(distance: number[], start: number, destination: number): number {
if (start > destination) [start, destination] = [destination, start];
const total = distance.reduce((sum, value) => sum + value, 0); let direct = 0; for (let stop = start; stop < destination; stop += 1) direct += distance[stop]; return Math.min(direct, total - direct);
}