Minimum Cost For Tickets - Problem

You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days. Each day is an integer from 1 to 365.

Train tickets are sold in three different ways:

  • A 1-day pass is sold for costs[0] dollars
  • A 7-day pass is sold for costs[1] dollars
  • A 30-day pass is sold for costs[2] dollars

The passes allow that many days of consecutive travel. For example, if we get a 7-day pass on day 2, then we can travel for 7 days: 2, 3, 4, 5, 6, 7, and 8.

Return the minimum number of dollars you need to travel every day in the given list of days.

Input & Output

Example 1 — Basic Case
$ Input: days = [1,4,6,7,8,20], costs = [2,7,15]
Output: 11
💡 Note: Buy 7-day pass on day 1 covering days 1,4,6,7,8 ($7) + 1-day pass on day 20 ($2) = $9. Wait, let me recalculate: 7-day pass covers 7 consecutive days from purchase. Day 1 pass covers days 1-7, so covers days 1,4,6,7. Day 8 needs separate pass. Better: 1-day passes for days 1,4,6 ($6) + 7-day pass on day 7 covers days 7,8 ($7) + 1-day pass day 20 ($2) = $15. Actually optimal: 7-day pass on day 1 covers days 1-7 ($7) + 1-day pass day 8 ($2) + 1-day pass day 20 ($2) = $11
Example 2 — 30-day Pass Optimal
$ Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]
Output: 17
💡 Note: 30-day pass on day 1 covers days 1-30 ($15) + 1-day pass on day 31 ($2) = $17. This beats buying multiple 7-day passes.
Example 3 — Sparse Travel Days
$ Input: days = [1,4,6,7,8,20], costs = [7,2,15]
Output: 6
💡 Note: When 7-day pass costs less than 1-day pass: 7-day pass on day 1 covers days 1-7 ($2) + 7-day pass on day 20 covers day 20 ($2) + 7-day pass on day 8 covers day 8 ($2) = $6

Constraints

  • 1 ≤ days.length ≤ 365
  • 1 ≤ days[i] ≤ 365
  • days is in strictly increasing order
  • costs.length == 3
  • 1 ≤ costs[i] ≤ 1000

Visualization

Tap to expand
Minimum Cost For Tickets: Choose Optimal Pass StrategyTravel Days:1467820Pass Options:1-day: $27-day: $730-day: $15Optimal Strategy:7-day pass on day 1 covers days 1,4,6,71-day: day 81-day: day 20Total Cost: $7 + $2 + $2 = $11
Understanding the Visualization
1
Input
Travel days [1,4,6,7,8,20] and costs [2,7,15] for 1/7/30-day passes
2
Process
For each day, choose cheapest pass option that covers it
3
Output
Minimum total cost $11
Key Takeaway
🎯 Key Insight: Use dynamic programming to choose the optimal pass for each day by comparing all three options and their future costs
Asked in
Google 25 Facebook 20 Amazon 18 Apple 15
185.4K Views
Medium Frequency
~25 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen