Time Travel Hours
Problem statement
You are given an integer array years describing the years that a time traveler must visit in order, starting at years[0].
For each consecutive pair:
- Traveling to the same year costs
0hours. - Traveling forward to a later year costs
1hour. - Traveling backward to an earlier year costs
2hours.
Return the total travel time for the complete journey.
Function
timeTravelHours(years: int[]) → intExamples
Example 1
years = [2000, 1990, 2005, 2050]return = 4Traveling from 2000 back to 1990 costs 2 hours. Traveling forward from 1990 to 2005 and then to 2050 costs 1 hour per trip, for a total of 4.
Example 2
years = [2000, 2021, 2005]return = 3Traveling forward from 2000 to 2021 costs 1 hour, and traveling backward from 2021 to 2005 costs 2 hours, for a total of 3.
Example 3
years = [2021, 2021, 2005]return = 2Staying in 2021 costs 0 hours, and traveling backward from 2021 to 2005 costs 2 hours.
Constraints
- 1 <= years.length <= 100
- 1 <= years[i] <= 104