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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code