Skip to content

Commit b6f3ab2

Browse files
authored
Create 01 - Recursive Approach (caused TLE).cpp
1 parent 97e96b7 commit b6f3ab2

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
public:
3+
// Recursive function to calculate the minimum cost starting from 'index'
4+
int getMinCost(vector<int>& days, vector<int>& costs, int n, int index) {
5+
// Base case: if the index is out of bounds, there is no cost
6+
if (index >= n)
7+
return 0;
8+
9+
// **Cost for a 1-day pass**:
10+
// Recursively calculate the cost for the next day and add the cost of a 1-day pass
11+
int cost1 = getMinCost(days, costs, n, index + 1) + costs[0];
12+
13+
// **Cost for a 7-day pass**:
14+
// Move forward to the first day that is not covered by a 7-day pass
15+
int i;
16+
for (i = index; i < n && days[i] < days[index] + 7; i++);
17+
// Recursively calculate the cost from that day and add the cost of a 7-day pass
18+
int cost7 = getMinCost(days, costs, n, i) + costs[1];
19+
20+
// **Cost for a 30-day pass**:
21+
// Move forward to the first day that is not covered by a 30-day pass
22+
for (i = index; i < n && days[i] < days[index] + 30; i++);
23+
// Recursively calculate the cost from that day and add the cost of a 30-day pass
24+
int cost30 = getMinCost(days, costs, n, i) + costs[2];
25+
26+
// Return the minimum of the three costs
27+
return min(cost1, min(cost7, cost30));
28+
}
29+
30+
// Main function to calculate the minimum cost of traveling
31+
int mincostTickets(vector<int>& days, vector<int>& costs) {
32+
// Start the calculation from the first day
33+
return getMinCost(days, costs, days.size(), 0);
34+
}
35+
};

0 commit comments

Comments
 (0)