Go•distance-between-bus-stops/solution.go
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
}
Python•distance-between-bus-stops/solution.py
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)
TypeScript•distance-between-bus-stops/solution.ts
function distanceBetweenBusStops(distance: number[], start: number, destination: number): number {
if (start > destination) [start, destination] = [destination, start];
const total = distance.reduce((sum, value) => sum + value, class="syntax-number">0); let direct = class="syntax-number">0; for (let stop = start; stop < destination; stop += class="syntax-number">1) direct += distance[stop]; return Math.min(direct, total - direct);
}