oneby7

1-D Dynamic Programming Take it or skip it

523. Minimum Cost For Tickets

Medium

You are given the days on which you will travel, days, as a strictly increasing list of day numbers. You are also given costs, the prices of three kinds of travel pass:

  • a 1-day pass costs costs[0],
  • a 7-day pass costs costs[1],
  • a 30-day pass costs costs[2].

A pass lasts for that many days in a row, counting the day you buy it. So a 7-day pass bought on day 10 covers days 10 to 16, and not day 17. You can buy as many passes as you like, on any days.

Return the smallest total cost of passes that covers every day in days.

Example 1

Input: days = [6, 13, 17, 19, 22, 33, 34] costs = [4, 7, 24]

Output: 22

Explanation: Buy a 1-day pass for day 6 (4), a 7-day pass on day 13 that covers 13, 17 and 19 (7), a 1-day pass for day 22 (4), and a 7-day pass on day 33 that covers 33 and 34 (7). That is 4 + 7 + 4 + 7 = 22. One 30-day pass cannot reach from day 6 to day 34.

Example 2

Input: days = [1, 1000000000], costs = [7, 2, 15]

Output: 4

Explanation: Here the 7-day pass costs less than the 1-day pass, so each travel day gets its own 7-day pass. The two days are too far apart for one pass to cover both.

Example 3

Input: days = [1, 10, 20, 30, 31], costs = [3, 9, 10]

Output: 13

Explanation: A 30-day pass bought on day 1 covers days 1 to 30, which holds four travel days, for 10. Day 31 is just outside it and needs a 1-day pass for 3.

Check your understanding

Work out the answer for this input before you write any code.

days = [1, 8, 20], costs = [6, 4, 31]

Constraints

  • 1 ≤ days.length ≤ 105
  • 1 ≤ days[i] ≤ 109
  • days is strictly increasing.
  • costs.length == 3
  • 1 ≤ costs[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.