Skip to content

solves minimum cost for tickets (#983) in python #15

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Mar 28, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions python/minimum_cost_for_tickets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# https://leetcode.com/problems/minimum-cost-for-tickets/description/
# T: O(N) where N is the last day of travel
# S: O(N) where N is the last day of travel

class Solution:
def mincostTickets(self, days, costs):
# Create a list of size days[-1] + 1 and initialize it with 0's
dp = [0] * (days[-1] + 1)

# Create a set of travel days
travel_days = set(days)

# Iterate over the range of 1 to len(dp) with a step of 1
for i in range(1, len(dp)):
# If the current day is not in the set of travel days
if i not in travel_days:
# Set its cost to the cost of traveling on the previous day
dp[i] = dp[i - 1]
else:
# Calculate the minimum cost for traveling on that day
dp[i] = min(dp[max(0, i - 1)] + costs[0],
dp[max(0, i - 7)] + costs[1],
dp[max(0, i - 30)] + costs[2])

# Return the last element of this list which will be the minimum cost of travel for all days
return dp[-1]