Advertisement
Fastrail08

Minimum Cost of Tickets

May 25th, 2025
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.26 KB | None | 0 0
  1. //QUESTION
  2. // https://leetcode.com/problems/minimum-cost-for-tickets/?envType=problem-list-v2&envId=9otti25c
  3.  
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6.  
  7. void getMinCostToTravel(int index, int currCost, int freeTravelUpto, int &minCost, vector<int> &days, vector<int> &cost){
  8.     //base case
  9.     if(index >= days.size()){
  10.         minCost = min(minCost, currCost);
  11.         return;
  12.     }
  13.     //level - each day
  14.     //options - each pass options tried on every level
  15.    
  16.     // if the day is not covered in the pass brought on a previous day, buy a new one (with every option each to generate all the possibilites)
  17.     if(days[index] > freeTravelUpto){
  18.         for(int i = 0; i < cost.size(); i++){
  19.             int pass = i == 0 ? 1 : i == 1 ? 7 : 30;
  20.             getMinCostToTravel(index + 1, currCost + cost[i], days[index] + (pass - 1), minCost, days, cost);  
  21.         }
  22.     }
  23.     // if the day is already covered by a pass brought on some previous day, don't buy,just move to next day
  24.     else{
  25.         getMinCostToTravel(index + 1, currCost, freeTravelUpto, minCost, days, cost);
  26.     }
  27. }
  28.  
  29. int getMinCostToTravelMemo (int index, int freeTravelUpto, vector<int> &days, vector<int> &cost){
  30.     //base case
  31.     if(index >= days.size()){
  32.         return 0;
  33.     }
  34.     int minCost = INT_MAX;
  35.     if(days[index] > freeTravelUpto){
  36.         for(int i = 0; i < cost.size(); i++){
  37.             int pass = i == 0 ? 1 : i == 1 ? 7 : 30;
  38.             minCost = min(minCost, cost[i] + getMinCostToTravelMemo(index + 1, days[index] + (pass - 1), days, cost));  
  39.         }
  40.     }
  41.     // if the day is already covered by a pass brought on some previous day, don't buy,just move to next day
  42.     else{
  43.         minCost = getMinCostToTravelMemo(index + 1, freeTravelUpto, days, cost);
  44.     }
  45.     return minCost;
  46. }
  47.  
  48. int main() {
  49.     // your code goes here
  50.     int n;
  51.     cin >> n;
  52.     vector<int> days(n), cost(3);
  53.     for(int i = 0; i < n; i++){
  54.         cin >> days[i];
  55.     }
  56.     for(int i = 0; i < n; i++){
  57.         cin >> cost[i];
  58.     }
  59.     int freeTravelUpto = 0, minCost = INT_MAX;
  60.     // getMinCostToTravel(0, 0, freeTravelUpto, minCost, days, cost);
  61.     // cout << minCost << '\n';
  62.    
  63.     cout << getMinCostToTravelMemo(0, freeTravelUpto, days, cost) << '\n';
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement