
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find minimum bus fare for travelling all days in Python?
Suppose we have a list of sorted numbers called days, where we must take the bus for on each day. We have to find the lowest cost it takes to travel for all the days. There are 3 types of bus tickets. 1-day pass for 2 bucks 7-day pass for 7 bucks 30-day pass for 25 bucks
So, if the input is like days = [1, 3, 5, 6, 28], then the output will be 9, as the lowest cost can be achieved by purchasing a 7-day pass in the beginning and then a 1-day pass on the 29th day.
To solve this, we will follow these steps:
n := maximum of days
days := a new set from days
dp := [0] *(n + 1)
for i in range 1 to n + 1, do
if i in days is non-zero, then
if i >= 30, then
dp[i] := minimum of dp[i - 1] + 2, dp[i - 7] + 7, dp[i - 30] + 25
otherwise when i >= 7, then
dp[i] := minimum of dp[i - 1] + 2, dp[i - 7] + 7, 25
otherwise,
dp[i] := minimum of dp[i - 1] + 2, 7
otherwise,
dp[i] := dp[i - 1]
return dp[n]
Let us see the following implementation to get better understanding:
Example
class Solution: def solve(self, days): n = max(days) days = set(days) dp = [0] * (n + 1) for i in range(1, n + 1): if i in days: if i >= 30: dp[i] = min(dp[i - 1] + 2, dp[i - 7] + 7, dp[i - 30] + 25) elif i >= 7: dp[i] = min(dp[i - 1] + 2, dp[i - 7] + 7, 25) else: dp[i] = min(dp[i - 1] + 2, 7) else: dp[i] = dp[i - 1] return dp[n] ob = Solution() days = [1, 3, 5, 6, 28] print(ob.solve(days))
Input
[1, 3, 5, 6, 28]
Output
9
- Related Questions & Answers
- Program to find minimum space plane required for skydivers in k days in python
- Program to find minimum number of days to eat N oranges in Python
- Program to find minimum number of days to wait to make profit in python
- Program to find minimum number of days to make m bouquets using Python
- Program to find minimum time to complete all tasks in python
- Program to find minimum cost to connect all points in Python
- Program to find minimum time to finish all jobs in Python
- Program to find minimum cost for painting houses in Python
- Program to find minimum value to insert at beginning for all positive prefix sums in Python
- Program to Find Out the Minimum Cost to Purchase All in Python
- C++ Program to Solve Travelling Salesman Problem for Unweighted Graph
- Program to find number of days it will take to burn all trees in python
- Program to find minimum swaps needed to group all 1s together in Python
- Program to find out the minimum path to deliver all letters in Python
- Program to find minimum total cost for equalizing list elements in Python