Calculate Total Distance Travelled
Giving position of trucks and they are always moving towards end station as it is a gas station. Given a second array indicating extra gas station position in 1-indexing. Calculate the total distance travelled by all the trucks.
Example: Given trucks at positions [0,2,5,9,12,18] and extra gas stations at positions
[[2,5],[3]], the answer to be returned is [12,18]. The solution can be
solved in O(n^2) time complexity with one for loop for traversing gas station array and
a second loop to calculate total distance travelled. However, there are test cases where this approach
may not be optimal.
Complete the function calculateTotalDistanceTravelled in the editor.
calculateTotalDistanceTravelled has the following parameters:
- 1.
int[] trucks: an array of integers indicating the initial positions of the trucks - 2.
int[][] extraGasStations: a 2D array of integers indicating the positions of extra gas stations
Returns
int[]: an array of integers indicating the total distance travelled by all the trucks
1Example 1
Constraints
Limits and guarantees your solution can rely on.
๐๐