# Minimum Cost For Tickets in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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 dollars;

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

• A 30-day pass is sold for costs 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 = $2, that is covering day 1, on day 3, we have bought 7 day pass, so cost =$7, that is covering days 3 to 9, and on day 20, again bought a pass for 1 day, so cost = $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 + dp[i - 1]

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

• if i – 30 >= 0, then dp[i] := minimum of dp[i - 30] + cost 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

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 + dp[i - 1];
if(i - 7 >= 0){
dp[i] = min(dp[i - 7] + costs, dp[i]);
}
if(i - 30 >= 0){
dp[i] = min(dp[i - 30] + costs, dp[i]);
}
if(j < days.size() && days[j] == i){
j++;
}else
dp[i] = min(dp[i], dp[i - 1]);
}
return dp;
}
};
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