#983

Minimum Cost For Tickets

Medium
ArrayDynamic ProgrammingDynamic ProgrammingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses dynamic programming to build up the minimum cost for each day based on previously computed results. This avoids redundant calculations and efficiently finds the minimum cost.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a DP array where dp[i] represents the minimum cost to travel up to day i.
  2. 2Step 2: Iterate through each travel day and update the DP array based on the cost of each ticket type.
  3. 3Step 3: Return the value in the DP array corresponding to the last travel day.
solution.py13 lines
1def mincostTickets(days, costs):
2    dp = [0] * 366
3    travel_days = set(days)
4    for day in range(1, 366):
5        if day in travel_days:
6            dp[day] = min(
7                dp[day - 1] + costs[0],
8                dp[max(0, day - 7)] + costs[1],
9                dp[max(0, day - 30)] + costs[2]
10            )
11        else:
12            dp[day] = dp[day - 1]
13    return dp[365]

Complexity note: The time complexity is O(n) because we iterate through each day of the year once, updating the DP array. The space complexity is O(n) due to the DP array storing costs for each day.

  • 1Dynamic programming helps avoid redundant calculations.
  • 2Understanding the problem constraints (days within 1-365) is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.