703389. Total distance travelled in an array
Total Distance Travelled in an Array
Summary
Given an array of integers, find the total distance travelled by an element. The distance is calculated as the absolute difference between consecutive elements. This problem involves basic algorithmic concepts like array manipulation and mathematical operations.
Detailed Explanation
The problem can be solved using a simple iteration through the array. For each pair of adjacent elements, calculate the absolute difference (distance) and add it to the total distance travelled.
Here's a step-by-step breakdown:
- Initialize a variable
total_distanceto 0. - Iterate through the array from index 1 to the second last element (since we're comparing adjacent elements).
- For each pair of adjacent elements, calculate the absolute difference (
distance) asabs(arr[i] - arr[i-1]). - Add the calculated distance to the total distance travelled:
total_distance += distance. - Return the final total distance travelled.
Time complexity analysis: The algorithm iterates through the array once, so the time complexity is O(n), where n is the size of the input array.
Space complexity analysis: The algorithm requires a single variable to store the total distance travelled, so the space complexity is O(1).
Optimized Solutions
Java
public int totalDistance(int[] arr) {
int total_distance = 0;
for (int i = 1; i < arr.length - 1; i++) {
int distance = Math.abs(arr[i] - arr[i-1]);
total_distance += distance;
}
return total_distance;
}