Minimum possible travel cost among N cities | Function to return the minimum cost to travel from the first city to the last ; To store the total cost ; Start from the first city ; If found any city with cost less than that of the previous boarded bus then change the bus ; Calculate the cost to travel from the currently boarded bus till the current city ; Update the currently boarded bus ; Finally calculate the cost for the last boarding bus till the ( N + 1 ) th city ; Driver code
function minCost ( cost , n ) { var totalCost = 0 ; var boardingBus = 0 ; for ( i = 1 ; i < n ; i ++ ) { if ( cost [ boardingBus ] > cost [ i ] ) { totalCost += ( ( i - boardingBus ) * cost [ boardingBus ] ) ; boardingBus = i ; } } totalCost += ( ( n - boardingBus ) * cost [ boardingBus ] ) ; return totalCost ; } var cost = [ 4 , 7 , 8 , 3 , 4 ] ; var n = cost . length ; document . write ( minCost ( cost , n ) ) ;