Minimum Cost for Tickets

Medium · Greedy · Array · Dynamic Programming

Problem

You have planned train trips on certain days of one year, given as the strictly increasing list days with values from 1 to 365.

Passes come in three kinds, priced by costs:

A pass bought on day d covers that many consecutive days starting at d (a 7-day pass bought on day 2 covers days 2 to 8). Return the minimum total cost to travel on every listed day.

Examples

Input: days = [1,3,5,20], costs = [3,10,25]
Output: 12

Three 1-day passes for days 1, 3 and 5 cost 9, less than a 7-day pass; day 20 adds 3.

Input: days = [2,3,4,5,6,7,30], costs = [2,7,20]
Output: 9

One 7-day pass on day 2 covers days 2 to 8, plus a 1-day pass on day 30.

Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]
Output: 17

A 30-day pass covers days 1 to 30 for 15, and a 1-day pass covers day 31 for 2.

Constraints

Approaches

Follow-up

What if trips span many years, so the calendar is huge but trips are few? Run the DP over the trips instead of the days: for trip i, three pointers give the first trip not covered by a 1-, 7- or 30-day pass starting at it. The pointers only move forward, so the work is O(n) in the number of trips, independent of the calendar length.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…