@@ -62,15 +62,16 @@ class Solution {
62
62
int mincostTickets (vector<int >& days, vector<int >& costs) {
63
63
64
64
// Dynamic Programming
65
- vector<int > dp (days.size (), INT_MAX);
65
+ vector<int > dp (days.size ()+ 1 , INT_MAX);
66
66
67
67
// dp[i] is the minimal cost from Days[0] to Days[i]
68
- dp[0 ] = costs[0 ];
68
+ dp[0 ] = 0 ;
69
+ dp[1 ] = min (costs[0 ], costs[1 ], costs[2 ]);
69
70
70
- for (int i = 1 ; i< days.size (); i ++) {
71
+ for (int i = 2 ; i<= days.size (); i ++) {
71
72
72
- // the currnet day need at least 1-day pass cost
73
- int OneDayPass = dp[i-1 ] + costs[0 ];
73
+ // the currnet day need at least min( 1-day, 7days, 30days) from previous.
74
+ int m = dp[i-1 ] + min ( costs[0 ], costs[ 1 ], costs[ 2 ]) ;
74
75
75
76
// Seprating the array to two parts.
76
77
// days[0] -> days[j] -> day[i]
@@ -79,21 +80,23 @@ class Solution {
79
80
//
80
81
// Traking the minimal costs, then can have dp[i] minimal cost
81
82
82
- int SevenDayPass = INT_MAX, ThrityDayPass = INT_MAX;
83
- for (int j=i-1 ; j>=0 ; j--){
84
- if (days[i] - days[j] < 7 ) {
85
- SevenDayPass = dp[j-1 ] + costs[1 ];
86
- } else if (days[i] - days[j] < 30 ) {
87
- ThrityDayPass = dp[j-1 ] + costs[2 ];
83
+ int SevenDays = INT_MAX, ThrityDays = INT_MAX;
84
+ for (int j=i-1 ; j>0 ; j--){
85
+ int gaps = days[i-1 ] - days[j-1 ];
86
+ if ( gaps < 7 ) {
87
+ // can use 7-days or 30-days ticket
88
+ SevenDays = dp[j-1 ] + min (costs[1 ], costs[2 ]);
89
+ } else if (gaps < 30 ) {
90
+ // can use 30-days tickets
91
+ ThrityDays = dp[j-1 ] + costs[2 ];
88
92
} else {
89
93
break ;
90
94
}
91
- int m = min (OneDayPass, SevenDayPass, ThrityDayPass);
92
- if ( dp[i] > m ) dp[i] = m;
95
+ m = min (m, SevenDays, ThrityDays);
93
96
}
94
-
97
+ if ( dp[i] > m ) dp[i] = m;
95
98
}
96
-
97
- return dp[dp.size ()-1 ];
99
+
100
+ return dp[dp.size ()-1 ];
98
101
}
99
102
};
0 commit comments