1
+ /*
2
+ 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.
3
+
4
+ Train tickets are sold in three different ways:
5
+
6
+ a 1-day pass is sold for costs[0] dollars,
7
+ a 7-day pass is sold for costs[1] dollars, and
8
+ a 30-day pass is sold for costs[2] dollars.
9
+ The passes allow that many days of consecutive travel.
10
+
11
+ Return the minimum number of dollars you need to travel every day in the given list of days.
12
+
13
+
14
+ Example. For days = [1,4,6,7,8,20] and costs = [2,7,15] we can buy a 1-day pass
15
+ for costs[0] = $2, which covers day 1. On day 3 we can buy a 7-day pass
16
+ for costs[1] = $7, which covers days 3,4....9. On day 20 we can again buy a
17
+ 1-day pass for costs[0] = $2 that will cover the 20th day. So in total we spent
18
+ 2 + 7 + 2 = $11 which is the minimum dollars needed for travelling in this case.
19
+
20
+
21
+ Time: O(n)
22
+ Space: O(n)
23
+
24
+ */
25
+
26
+
27
+ class Solution {
28
+ public:
29
+ int mincostTickets (vector<int >& days, vector<int >& costs) {
30
+
31
+ vector<int > dp (days.size () + 1 , 1e9 );
32
+ dp[days.size ()] = 0 ;
33
+ for (int i=days.size ()-1 ; i>=0 ; i--) {
34
+ for (int j=0 ; j<3 ; j++) {
35
+ if (j == 0 ) {
36
+ auto it = lower_bound (days.begin ()+i, days.end (), days[i]+1 );
37
+ dp[i] = min (dp[i], costs[j] + dp[it-days.begin ()]);
38
+ }
39
+ else if (j == 1 ) {
40
+ auto it = lower_bound (days.begin ()+i, days.end (), days[i]+7 );
41
+ dp[i] = min (dp[i], costs[j] + dp[it-days.begin ()]);
42
+ } else {
43
+ auto it = lower_bound (days.begin ()+i, days.end (), days[i]+30 );
44
+ dp[i] = min (dp[i], costs[j] + dp[it-days.begin ()]);
45
+ }
46
+ }
47
+ }
48
+ return dp[0 ];
49
+
50
+ }
51
+ };
0 commit comments