Skip to content

Commit a159d1b

Browse files
solves minimum cost for tickets (#983) in python
1 parent cb54e2a commit a159d1b

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Diff for: python/minimum_cost_for_tickets.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# https://leetcode.com/problems/minimum-cost-for-tickets/description/
2+
# T: O(N) where N is the last day of travel
3+
# S: O(N) where N is the last day of travel
4+
5+
class Solution:
6+
def mincostTickets(self, days, costs):
7+
# Create a list of size days[-1] + 1 and initialize it with 0's
8+
dp = [0] * (days[-1] + 1)
9+
10+
# Create a set of travel days
11+
travel_days = set(days)
12+
13+
# Iterate over the range of 1 to len(dp) with a step of 1
14+
for i in range(1, len(dp)):
15+
# If the current day is not in the set of travel days
16+
if i not in travel_days:
17+
# Set its cost to the cost of traveling on the previous day
18+
dp[i] = dp[i - 1]
19+
else:
20+
# Calculate the minimum cost for traveling on that day
21+
dp[i] = min(dp[max(0, i - 1)] + costs[0],
22+
dp[max(0, i - 7)] + costs[1],
23+
dp[max(0, i - 30)] + costs[2])
24+
25+
# Return the last element of this list which will be the minimum cost of travel for all days
26+
return dp[-1]

0 commit comments

Comments
 (0)