Minimum Cost For Tickets in C++

C++Server Side ProgrammingProgramming

Suppose there is a country, that is popular for train travel, we have planned some train travelling one year in advance. We have an array, that is holding the days of the year that we will travel. Each day is an integer from 1 to 365. Train tickets are sold in three different ways −

  • A 1-day pass is sold for costs[0] dollars;

  • A 1-day pass is sold for costs[0] dollars;

  • A 30-day pass is sold for costs[2] dollars.

Here the passes allow that many days of consecutive travel. For example, if we get one 7-day pass on day 2, then we can travel for 7 days: day consecutively (2, 3, 4, 5, 6, 7, and 8). We have to find the minimum number of dollars we need to travel every day in the given list of days. So if the input is like [1,4,6,7,8,20] and costs are [2,7,15], then the output will be 11.

On day 1, we have bought 1 day pass for costs[0] = $2, that is covering day 1, on day 3, we have bought 7 day pass, so cost[1] = $7, that is covering days 3 to 9, and on day 20, again bought a pass for 1 day, so cost[0] = $2, that is covering day 20. So in total $11 are spent.

To solve this, we will follow these steps −

  • create one array called dp, of size 366

  • j := 0

  • for i in range 1 to 366

    • dp[i] := cost[0] + dp[i - 1]

    • if i – 7 >= 0, then dp[i] := minimum of dp[i - 7] + cost[1] and dp[i]

    • if i – 30 >= 0, then dp[i] := minimum of dp[i - 30] + cost[2] and dp[i]

    • if j < size of the days array and days[j] = i, then increase j by 1, otherwise dp[i] := minimum of dp[i], dp[i – 1]

  • return dp[365]

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int mincostTickets(vector<int>& days, vector<int>& costs) {
      vector <int> dp(366);
      int j = 0;
      for(int i = 1; i < 366; i++){
         dp[i] = costs[0] + dp[i - 1];
         if(i - 7 >= 0){
            dp[i] = min(dp[i - 7] + costs[1], dp[i]);
         }
         if(i - 30 >= 0){
            dp[i] = min(dp[i - 30] + costs[2], dp[i]);
         }
         if(j < days.size() && days[j] == i){
            j++;
         }else
            dp[i] = min(dp[i], dp[i - 1]);
      }
      return dp[365];
   }
};
main(){
   vector<int> v = {1,4,6,7,8,20};
   vector<int> v1 = {2,7,15};
   Solution ob;
   cout << (ob.mincostTickets(v, v1));
}

Input

[1,4,6,7,8,20]
[2,7,15]

Output

11
raja
Published on 05-Mar-2020 06:13:19
Advertisements