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
def minCost ( cost , n ) : NEW_LINE INDENT totalCost = 0 NEW_LINE boardingBus = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( cost [ boardingBus ] > cost [ i ] ) : NEW_LINE INDENT totalCost += ( ( i - boardingBus ) * cost [ boardingBus ] ) NEW_LINE boardingBus = i NEW_LINE DEDENT DEDENT totalCost += ( ( n - boardingBus ) * cost [ boardingBus ] ) NEW_LINE return totalCost NEW_LINE DEDENT cost = [ 4 , 7 , 8 , 3 , 4 ] NEW_LINE n = len ( cost ) NEW_LINE print ( minCost ( cost , n ) ) NEW_LINE