Ride-hailing app~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-983dp
A ride-hailing app sells passes for its scooters. A 1-day pass covers one day, a 7-day pass covers seven days in a row, and a 30-day pass covers thirty days in a row. A pass bought for a day covers that day and the days after it.
A rider knows the days of the year on which they will travel. Your team lead asks: "What is the least the rider pays to cover every travel day?"
Write cheapest_passes(days, costs).
days lists the travel days of the year, in increasing order, each from 1 to 365.costs[0], costs[1] and costs[2] are the prices of the 1-day, 7-day and 30-day pass.d covers days d to d + length - 1. Every travel day must be covered. Passes may overlap.Input: days = [2, 3, 5, 6, 7, 8, 12, 25], costs = [3, 11, 25]
Output: 17Let best[i] be the cheapest cost to cover the first i travel days. Think of the last pass as ending on travel day i - 1. A pass of length L covers every travel day after days[i - 1] - L.
Say those start at travel day first. Then the cost is best[first] + price, and best[i] is the smallest of the three.
| i | Day | 1-day: first, best[first] + cost | 7-day | 30-day | best[i] |
|---|---|---|---|---|---|
| 0 | none | 0 | |||
| 1 | 2 | 0: 0 + 3 = 3 | 0: 0 + 11 = 11 | 0: 0 + 25 = 25 | 3 |
| 2 | 3 | 1: 3 + 3 = 6 | 0: 0 + 11 = 11 | 0: 0 + 25 = 25 | 6 |
| 3 | 5 | 2: 6 + 3 = 9 | 0: 0 + 11 = 11 | 0: 0 + 25 = 25 | 9 |
| 4 | 6 | 3: 9 + 3 = 12 | 0: 0 + 11 = 11 | 0: 0 + 25 = 25 | 11 |
| 5 | 7 | 4: 11 + 3 = 14 | 0: 0 + 11 = 11 | 0: 0 + 25 = 25 | 11 |
| 6 | 8 | 5: 11 + 3 = 14 | 0: 0 + 11 = 11 | 0: 0 + 25 = 25 | 11 |
| 7 | 12 | 6: 11 + 3 = 14 | 3: 9 + 11 = 20 | 0: 0 + 25 = 25 | 14 |
| 8 | 25 | 7: 14 + 3 = 17 | 7: 14 + 11 = 25 | 0: 0 + 25 = 25 | 17 |
The answer is best[8] = 17.
Input: days = [1, 2, 3], costs = [5, 6, 7]
Output: 6The 7-day pass covers all three days for 6. Three 1-day passes cost 15.
Input: days = [1, 31], costs = [4, 9, 12]
Output: 8The days are 30 apart, so one 30-day pass cannot cover both. Two 1-day passes cost 8.
1 ≤ len(days) ≤ 365, and days is strictly increasing.1 ≤ days[i] ≤ 365len(costs) = 3, and 1 ≤ costs[k] ≤ 1000. A longer pass is not always cheaper than a shorter one.There are at most 365 travel days and 3 passes. Each day offers 3 choices, so trying every choice can take about 3 to the power 365 steps. A table with one entry for each travel day takes at most about 33,000 steps. Each of the 3 passes looks back over at most 30 travel days.