Skip to content

1184. Distance Between Bus Stops 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int distanceBetweenBusStops(vector<int>& distance, int start,
                              int destination) {
    int clockwise = 0;
    int counterclockwise = 0;

    if (start > destination)
      swap(start, destination);

    for (int i = 0; i < distance.size(); ++i) {
      if (i >= start && i < destination)
        clockwise += distance[i];
      else
        counterclockwise += distance[i];
    }

    return min(clockwise, counterclockwise);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int distanceBetweenBusStops(int[] distance, int start, int destination) {
    int clockwise = 0;
    int counterclockwise = 0;

    if (start > destination) {
      int temp = start;
      start = destination;
      destination = temp;
    }

    for (int i = 0; i < distance.length; ++i) {
      if (i >= start && i < destination)
        clockwise += distance[i];
      else
        counterclockwise += distance[i];
    }

    return Math.min(clockwise, counterclockwise);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def distanceBetweenBusStops(
      self,
      distance: list[int],
      start: int, destination: int,
  ) -> int:
    clockwise = 0
    counterclockwise = 0

    if start > destination:
      start, destination = destination, start

    for i, d in enumerate(distance):
      if i >= start and i < destination:
        clockwise += d
      else:
        counterclockwise += d

    return min(clockwise, counterclockwise)