Find the minimum cost to cross the River | Function to return the minimum cost ; Sort the price array ; Calculate minimum price of n - 2 most costly person ; Both the ways as discussed above ; Calculate the minimum price of the two cheapest person ; Driver code
function minimumCost ( price , n ) { price . sort ( ) ; let totalCost = 0 ; for ( let i = n - 1 ; i > 1 ; i -= 2 ) { if ( i == 2 ) { totalCost += price [ 2 ] + price [ 0 ] ; } else { let price_first = price [ i ] + price [ 0 ] + 2 * price [ 1 ] ; let price_second = price [ i ] + price [ i - 1 ] + 2 * price [ 0 ] ; totalCost += Math . min ( price_first , price_second ) ; } } if ( n == 1 ) { totalCost += price [ 0 ] ; } else { totalCost += price [ 1 ] ; } return totalCost ; } let price = [ 30 , 40 , 60 , 70 ] ; let n = price . length ; document . write ( minimumCost ( price , n ) ) ;