Find the minimum cost to reach destination using a train

There are ‘N’ stations on the route of a train. The train goes from station 0 to ‘N’ - 1. The ticket cost for all pairs of stations (i, j) is given where ‘j’ is greater than ‘i’. Your task is to find the minimum cost to reach the Nth station.

Note:

Cost of entries where j < i  will be represented as INT_MAX VALUE which is 10000 in the price matrix.
Example:
If ‘N’ = 3

'PRICE[3][3]' = {{0, 15, 80,},
               {INF, 0, 40},
               {INF, INF, 0}};

First, go from 1st station to 2nd at 15 costs, then go from 2nd to 3rd at 40. 15 + 40 = 55 is the total cost.It is cheaper than going directly from station 1 to station 3 as it would have cost 80.

The output will be 55.
Input format :
The first line of input contains an integer 'T' denoting the number of test cases. 

The first line of each test case contains a single integer 'N', Where ‘N’ is the number of rows and columns in the ‘PRICE’ matrix.

The next ‘N’ lines is as follows: Each line contains ‘N’ space-separated integers representing the cost of pairs (i,j) where ‘i’ and ‘j’ are indices of the matrix ‘PRICE’. 
Output format :
For each test case, return the minimum price that will have to be paid such that the train reaches from 1st to 'N'th station.

Print the output for each test case in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 100
1 <= N <= 1000

Time Limit: 1 sec
CodingNinjas
author
2y

The solution is to use DP and create a 2D table and fill the table using above given recursive formula.
minCost(0, N-1) = MIN { cost[0][n-1], cost[0][1] + minCost(1, N-1), ........, minCost(0, N-2) + c...read more

CodingNinjas
author
2y
Floyd Warshall Algorithm

The idea is to calculate the minimum price between all pair of stations using Floyd Warshall Algorithm:

  • Pick all vertices and update all minimum-cost-paths that include the sel...read more
CodingNinjas
author
2y
Topological Sort on Directed Acyclic Graph(DAG)

The idea is based on the fact that the given input matrix is a Directed Acyclic Graph (DAG) because we can go from a smaller station to another and not ...read more

Add answer anonymously...
Deutsche Bank Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter