Minimize cost to reach end of an N | Function to calculate the minimum cost required to reach the end of Line ; Checks if possible to reach end or not ; Stores the stations and respective rate of fuel ; Stores the station index and cost of fuel and litres of petrol which is being fueled ; Iterate through the entire line ; Check if there is a station at current index ; Remove all the stations where fuel cannot be pumped ; If there is no station left to fill fuel in tank , it is not possible to reach end ; Stores the best station visited so far ; Pump fuel from the best station ; Update the count of litres taken from that station ; Update the bunk in queue ; Print the cost ; Given value of N , K & M ; Given arrays ; Function call to calculate minimum cost to reach end of the line
function minCost ( N , K , M , a , b ) { var flag = true ; var map = new Map ( ) ; for ( var i = 0 ; i < M ; i ++ ) { map . set ( a [ i ] , b [ i ] ) ; if ( i == M - 1 && K < N - a [ i ] ) { flag = false ; break ; } else if ( i < M - 1 && K < a [ i + 1 ] - a [ i ] ) { flag = false ; break ; } } if ( ! flag ) { document . write ( - 1 ) ; return ; } var pq = [ ] ; var cost = 0 ; flag = false ; for ( var i = 0 ; i < N ; i ++ ) { if ( map . has ( i ) ) { var arr = [ i , map . get ( i ) , 0 ] ; pq . push ( arr ) ; } pq . sort ( ) ; while ( pq . length > 0 && pq [ pq . length - 1 ] [ 2 ] == K ) pq . pop ( ) ; if ( pq . length == 0 ) { flag = true ; break ; } var best_bunk = pq [ pq . length - 1 ] ; pq . pop ( ) ; cost += best_bunk [ 1 ] ; best_bunk [ 2 ] ++ ; pq . push ( best_bunk ) ; pq . sort ( ) ; } if ( flag ) { document . write ( - 1 + " " ) ; return ; } document . write ( cost + " " ) ; } var N = 10 , K = 3 , M = 4 ; var a = [ 0 , 1 , 4 , 6 ] ; var b = [ 5 , 2 , 2 , 4 ] ; minCost ( N , K , M , a , b ) ;