Last Updated: 8 Sep, 2025

Minimum Cost to Reach Destination in Time

Hard
Asked in company
PhonePe

Problem statement

You are given a country of 'n' cities, a series of bi-directional roads, and a list of passing fees for each city. The journey starts at city 0 and must end at city n-1 within a given maxTime.

The details are as follows:


  • The roads are given as a 2D array edges, where edges[i] = [u, v, time] represents a road between city u and v that takes time minutes to travel.

  • The cost of visiting any city is given in the passingFees array.

  • The total cost of a journey is the sum of the passing fees of all unique cities visited, including the start and end cities.

  • The total time of a journey is the sum of the travel times of all roads used.

  • Your task is to find the path from city 0 to city n-1 that has the minimum possible cost, while ensuring the total time does not exceed maxTime. If no such path exists, return -1.


    Input Format:
    The first line of input contains three space-separated integers: n (number of cities), E (number of edges), and maxTime.
    
    The second line contains 'n' space-separated integers, representing the passingFees array.
    
    The next 'E' lines each contain three space-separated integers: u, v, and time.
    


    Output Format:
    Print a single integer representing the minimum cost of a valid journey.
    
    If no valid journey exists, print -1.
    


    Note:
    This problem is a variation of the shortest path problem. A standard algorithm like Dijkstra's must be modified.
    
    The state in our search cannot just be the current city. We need to track the minimum time to reach each city.
    
    A priority queue should be used, but it should prioritize states with the minimum cost, as that is what we want to optimize. The state in the queue would be (current_cost, current_time, current_city).
    
    An auxiliary array, min_time[city], is needed to keep track of the minimum time found so far to reach each city. This helps prune paths that are both slower and more expensive.