Problem ¡ Array
● EasyZipRecruiterINTERNOA

Problem statement

Feel free to checkout the image source at the bottom of the page for the original problem statement 🦋

Imagine you’ve got a fantastic time machine at your disposal, and you’re on a grand journey through history. You’re given a list of years in which you must travel, starting from the year years[0]. Your adventure involves hopping from one year to the next in the sequence, and each leg of your journey has its own time cost: If you travel from one year to the exact same year, it takes you 0 hours (you’re already there!). If you move forward in time to a future year, it takes you 1 hour. If you journey backward to a past year, it takes you 2 hours. Your task is to calculate the total time required to complete your journey through all the years in the list, traveling in the given order. To sum up, you need to figure out how much time you’ll spend traveling between each pair of years, according to these rules. Your solution should be efficient enough to handle the task within the time constraints, even if it’s not the absolute fastest. So, set your time machine to work and calculate the total time for your historical adventure!

Function

ziprecruiterTimeTravel(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 ZipRecruiter problems

    drafts saved locally
    public int ziprecruiterTimeTravel(int[] years) {
      // write your code here
    }
    
    years[2000, 1990, 2005, 2050]
    expected4
    checking account