Skip to content

Commit 3b5b60a

Browse files
authored
Create distance-between-bus-stops.cpp
1 parent 1e6b9bc commit 3b5b60a

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

C++/distance-between-bus-stops.cpp

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int distanceBetweenBusStops(vector<int>& distance, int start, int destination) {
7+
if (start > destination) {
8+
swap(start, destination);
9+
}
10+
const auto& s_to_d = accumulate(distance.cbegin() + start,
11+
distance.cbegin() + destination, 0);
12+
const auto& d_to_s = accumulate(distance.cbegin(),
13+
distance.cbegin() + start, 0) +
14+
accumulate(distance.cbegin() + destination,
15+
distance.cend(), 0);
16+
return min(s_to_d, d_to_s);
17+
}
18+
};

0 commit comments

Comments
 (0)