Skip to content

Commit 5183dad

Browse files
committed
fix the problem - out of array boundary, and unresonalble ticket price "[7,2,15]". close haoel#243
1 parent ff70235 commit 5183dad

File tree

1 file changed

+19
-16
lines changed

1 file changed

+19
-16
lines changed

algorithms/cpp/minimumCostForTickets/MinimumCostForTickets.cpp

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -62,15 +62,16 @@ class Solution {
6262
int mincostTickets(vector<int>& days, vector<int>& costs) {
6363

6464
// Dynamic Programming
65-
vector<int> dp(days.size(), INT_MAX);
65+
vector<int> dp(days.size()+1, INT_MAX);
6666

6767
// 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]);
6970

70-
for (int i = 1; i< days.size(); i ++) {
71+
for (int i = 2; i<= days.size(); i ++) {
7172

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]);
7475

7576
// Seprating the array to two parts.
7677
// days[0] -> days[j] -> day[i]
@@ -79,21 +80,23 @@ class Solution {
7980
//
8081
// Traking the minimal costs, then can have dp[i] minimal cost
8182

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];
8892
} else {
8993
break;
9094
}
91-
int m = min(OneDayPass, SevenDayPass, ThrityDayPass);
92-
if ( dp[i] > m ) dp[i] = m;
95+
m = min(m, SevenDays, ThrityDays);
9396
}
94-
97+
if ( dp[i] > m ) dp[i] = m;
9598
}
96-
97-
return dp[dp.size()-1];
99+
100+
return dp[dp.size()-1];
98101
}
99102
};

0 commit comments

Comments
 (0)