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

 Live Demo

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

Updated on: 10-Nov-2020

689 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements