FastPrepTime Travel Hours

Time Travel Hours

Visa logoVisa● EasyFULLTIMEOA
Learn

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 0 hours.
  • Traveling forward to a later year costs 1 hour.
  • Traveling backward to an earlier year costs 2 hours.

Return the total travel time for the complete journey.

Function

timeTravelHours(years: int[]) → int

Examples

Example 1

years = [2000, 1990, 2005, 2050]return = 4

Traveling 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 = 3

Traveling 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 = 2

Staying in 2021 costs 0 hours, and traveling backward from 2021 to 2005 costs 2 hours.

Constraints

  • 1 <= years.length <= 100
  • 1 <= years[i] <= 104

More Visa problems

See Visa hiring insights
public int timeTravelHours(int[] years) {
    // Write your code here.
}
years[2000, 1990, 2005, 2050]
expected4
Checking account…