
Sponsored
Sponsored
This approach uses dynamic programming to maintain a cost array where each cell represents the minimum cost to travel up to that day. For each travel day, you decide to either buy a 1-day, 7-day, or 30-day pass and record the cost accordingly.
Time Complexity: O(n) where n is the last travel day. Space Complexity: O(n) for the DP array.
1
The JavaScript implementation follows a similar pattern to other dynamic programming solutions, tracking the minimum cost up to the last travel day. It uses, Map to quickly determine travel days and handles each travel day dynamically by checking the cost using 1, 7, or 30 day passes.
This approach uses recursion with memoization to explore each travel day recursively, storing intermediate results to avoid redundant calculations. It offers a top-down perspective on decision-making for ticket purchasing.
Time Complexity: O(n) where n is the number of travel days due to memoization. Space Complexity: O(n) for the memo array.
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5int dfs(int *days, int daysSize, int *costs, int start, int* memo) {
6 if (start >= daysSize) return 0;
7 if (memo[start] != -1) return memo[start];
8
9 int oneDay = costs[0] + dfs(days, daysSize, costs, start + 1, memo);
10 int i;
11 for (i = start; i < daysSize && days[i] < days[start] + 7; i++);
12 int sevenDay = costs[1] + dfs(days, daysSize, costs, i, memo);
13 for (i = start; i < daysSize && days[i] < days[start] + 30; i++);
14 int thirtyDay = costs[2] + dfs(days, daysSize, costs, i, memo);
15
16 return memo[start] = fmin(oneDay, fmin(sevenDay, thirtyDay));
17}
18
19int mincostTickets(int* days, int daysSize, int* costs, int costsSize) {
20 int memo[daysSize];
21 memset(memo, -1, sizeof(memo));
22 return dfs(days, daysSize, costs, 0, memo);
23}
24
25int main() {
26 int days[] = {1, 4, 6, 7, 8, 20};
27 int costs[] = {2, 7, 15};
28 int result = mincostTickets(days, 6, costs, 3);
29 printf("Minimum cost to travel is %d\n", result);
30 return 0;
31}This C implementation uses recursive depth-first search (DFS) with memoization to explore and store results of subproblems, reducing redundant calculations. The function calculates the minimum cost by considering costs of possible travel passes starting at each travel day index.
Solve with full IDE support and test cases