 GFG App
Open App Browser
Continue

# Minimize cost to reach end of an N-length straight path

Given an integer K denoting the fuel tank capacity of a car running at the cost of 1 liter / mtr on a straight path of length N meters and two arrays a[] and b[], each of size M, where a[i] denotes the location of the ith station and b[i] denotes the cost of 1-liter of fuel at that station. The task is to find the minimum cost required to reach the end of the line, starting from 0. If it is not possible to reach the end, then print -1.

Examples:

Input: N = 10, K = 10, M = 2, a[] = {0, 1}, b[] = {5, 2}
Output: 23
Explanation:
At the 0th location, fill the car tank with 1 liter of fuel at cost 5. Then, at 1st location, fill 9 liters of fuel at cost 18.
Therefore, the minimum cost required is 23.

Input: N = 10, K = 5, M = 3, a[] = {0, 3, 5}, b[] = {5, 9, 3}
Output: 40

Approach: The idea is to use Priority Queue and HashMap to store the fuel stations in order to get the fuel station with minimum cost. Follow the steps below to solve the problem:

• Initialize a HashMap, say map, to store the index of the station and its respective rate of fuel.
• Initialize a Priority Queue, say pq, to store the station’s index and cost of fuel and liters of fuel that is being filled.
• Initialize two variables, say cost, to store the minimum cost required, and set flag = false to check if there are any filling stations or not.
• Iterate over the range [1, N]:
• Check if there is a station or not. If found to be true, then insert it into pq.
• Remove all the stations where fuel cannot be filled.
• If pq is empty, then it is not possible to reach the end of line. Therefore, set flag = true.
• Store the least cost station and update the cost and the number of liters pumped from that particular station.
• Insert it again into pq.
• If flag is true, then print “-1”. It means there are no filling stations. Therefore, it is not possible to reach end of line.
• Otherwise, print the minimum cost to reach the end of the line.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ` `using` `namespace` `std;`   `// For priority_queue` `struct` `Compare {` `  ``bool` `operator()(array<``int``, 3> a, array<``int``, 3> b)` `  ``{` `    ``return` `a > b;` `  ``}` `};`   `// Function to calculate the minimum cost` `// required to reach the end of Line` `void` `minCost(``int` `N, ``int` `K, ``int` `M, ``int` `a[], ``int` `b[])` `{` `  ``// Checks if possible to` `  ``// reach end or not` `  ``bool` `flag = ``true``;`   `  ``// Stores the stations and` `  ``// respective rate of fuel` `  ``unordered_map<``int``, ``int``> map;` `  ``for` `(``int` `i = 0; i < M; i++) {` `    ``map[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) {` `    ``cout << -1;` `    ``return``;` `  ``}`   `  ``// Stores the station index and cost of fuel and` `  ``// litres of petrol which is being fueled` `  ``priority_queue, vector >,` `  ``Compare>` `    ``pq;` `  ``int` `cost = 0;` `  ``flag = ``false``;`   `  ``// Iterate through the entire line` `  ``for` `(``int` `i = 0; i < N; i++) {`   `    ``// Check if there is a station at current index` `    ``if` `(map.find(i) != map.end()) {` `      ``array<``int``, 3> arr = { i, map[i], 0 };` `      ``pq.push(arr);` `    ``}`   `    ``// Remove all the stations where` `    ``// fuel cannot be pumped` `    ``while` `(pq.size() > 0 && pq.top() == K)` `      ``pq.pop();`   `    ``// If there is no station left to fill fuel` `    ``// in tank, it is not possible to reach end` `    ``if` `(pq.size() == 0) {` `      ``flag = ``true``;` `      ``break``;` `    ``}`   `    ``// Stores the best station` `    ``// visited so far` `    ``array<``int``, 3> best_bunk = pq.top();` `    ``pq.pop();`   `    ``// Pump fuel from the best station` `    ``cost += best_bunk;`   `    ``// Update the count of litres` `    ``// taken from that station` `    ``best_bunk++;`   `    ``// Update the bunk in queue` `    ``pq.push(best_bunk);` `  ``}` `  ``if` `(flag) {` `    ``cout << -1 << ``"\n"``;` `    ``return``;` `  ``}`   `  ``// Print the cost` `  ``cout << cost << ``"\n"``;` `}`   `// Driven Program` `int` `main()` `{`   `  ``// Given value of N, K & M` `  ``int` `N = 10, K = 3, M = 4;`   `  ``// Given arrays` `  ``int` `a[] = { 0, 1, 4, 6 };` `  ``int` `b[] = { 5, 2, 2, 4 };`   `  ``// Function call to calculate minimum` `  ``// cost to reach end of the line` `  ``minCost(N, K, M, a, b);`   `  ``return` `0;` `}`   `// This code is contributed by Kingash.`

## Java

 `// Java program for the above approach`   `import` `java.util.*;` `public` `class` `Main {`   `    ``// Function to calculate the minimum cost` `    ``// required to reach the end of Line` `    ``static` `void` `minCost(``int` `N, ``int` `K, ``int` `M,` `                        ``int``[] a, ``int``[] b)` `    ``{` `        ``// Checks if possible to` `        ``// reach end or not` `        ``boolean` `flag = ``true``;`   `        ``// Stores the stations and` `        ``// respective rate of fuel` `        ``HashMap map = ``new` `HashMap<>();` `        ``for` `(``int` `i = ``0``; i < M; i++) {` `            ``map.put(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) {` `            ``System.out.println(``"-1"``);` `            ``return``;` `        ``}`   `        ``// Stores the station index and cost of fuel and` `        ``// litres of petrol which is being fueled` `        ``PriorityQueue<``int``[]> pq` `            ``= ``new` `PriorityQueue<>((c, d) -> c[``1``] - d[``1``]);` `        ``int` `cost = ``0``;` `        ``flag = ``false``;`   `        ``// Iterate through the entire line` `        ``for` `(``int` `i = ``0``; i < N; i++) {`   `            ``// Check if there is a station at current index` `            ``if` `(map.containsKey(i))` `                ``pq.add(``new` `int``[] { i, map.get(i), ``0` `});`   `            ``// Remove all the stations where` `            ``// fuel cannot be pumped` `            ``while` `(pq.size() > ``0` `&& pq.peek()[``2``] == K)` `                ``pq.poll();`   `            ``// If there is no station left to fill fuel` `            ``// in tank, it is not possible to reach end` `            ``if` `(pq.size() == ``0``) {` `                ``flag = ``true``;` `                ``break``;` `            ``}`   `            ``// Stores the best station` `            ``// visited so far` `            ``int` `best_bunk[] = pq.poll();`   `            ``// Pump fuel from the best station` `            ``cost += best_bunk[``1``];`   `            ``// Update the count of litres` `            ``// taken from that station` `            ``best_bunk[``2``]++;`   `            ``// Update the bunk in queue` `            ``pq.add(best_bunk);` `        ``}` `        ``if` `(flag) {` `            ``System.out.println(``"-1"``);` `            ``return``;` `        ``}`   `        ``// Print the cost` `        ``System.out.println(cost);` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `main(String args[])` `    ``{` `        ``// Given value of N, K & M` `        ``int` `N = ``10``, K = ``3``, M = ``4``;`   `        ``// Given arrays` `        ``int` `a[] = { ``0``, ``1``, ``4``, ``6` `};` `        ``int` `b[] = { ``5``, ``2``, ``2``, ``4` `};`   `        ``// Function call to calculate minimum` `        ``// cost to reach end of the line` `        ``minCost(N, K, M, a, b);` `    ``}` `}`

## Python3

 `# Python3 program for the above approach`   `# Function to calculate the minimum cost` `# required to reach the end of Line` `def` `minCost(N, K, M, a, b):`   `  ``# Checks if possible to` `  ``# reach end or not` `  ``flag ``=` `True`   `  ``# Stores the stations and` `  ``# respective rate of fuel` `  ``map` `=` `{}` `  ``for` `i ``in` `range``(M):` `    ``map``[a[i]] ``=` `b[i]` `    ``if` `(i ``=``=` `M ``-` `1` `and` `K < N ``-` `a[i]):` `      ``flag ``=` `False` `      ``break` `    `  `    ``elif` `(i < M ``-` `1` `and` `K < a[i ``+` `1``] ``-` `a[i]):` `      ``flag ``=` `False` `      ``break` `    `  `  ``if` `(flag ``=``=` `0``):` `        ``print``(``-``1``)` `        ``return`   `  ``# Stores the station index and cost of fuel and` `  ``# litres of petrol which is being fueled` `  ``pq ``=` `[]` `  ``cost ``=` `0` `  ``flag ``=` `False`   `  ``# Iterate through the entire line` `  ``for` `i ``in` `range``(N):`   `    ``# Check if there is a station at current index` `    ``if` `(i ``in` `map``):` `      ``arr ``=` `[ i, ``map``[i], ``0` `]` `      ``pq.append(arr)`   `    ``pq.sort()` `    `  `    ``# Remove all the stations where` `    ``# fuel cannot be pumped` `    ``while` `(``len``(pq) > ``0` `and` `pq[``-``1``][``2``] ``=``=` `K):` `      ``pq.pop()`   `    ``# If there is no station left to fill fuel` `    ``# in tank, it is not possible to reach end` `    ``if` `(``len``(pq) ``=``=` `0``):` `      ``flag ``=` `True` `      ``break` `    `  `    ``# Stores the best station` `    ``# visited so far` `    ``best_bunk ``=` `pq[``len``(pq)``-``1``]` `    ``pq.pop()`   `    ``# Pump fuel from the best station` `    ``cost ``+``=` `best_bunk[``1``]`   `    ``# Update the count of litres` `    ``# taken from that station` `    ``best_bunk[``2``] ``+``=` `1`   `    ``# Update the bunk in queue` `    ``pq.append(best_bunk)` `    ``pq.sort()` `  `  `  ``if` `(flag):` `      ``print``( ``-``1``)` `      ``return`   `  ``# Print the cost` `  ``print``(cost)`   `# Driven Program` `# Given value of N, K & M` `N,K,M ``=` `10``,``3``,``4`   `# Given arrays` `a ``=` `[``0``, ``1``, ``4``, ``6``]` `b ``=` `[``5``, ``2``, ``2``, ``4``]`   `# Function call to calculate minimum` `# cost to reach end of the line` `minCost(N, K, M, a, b)`   `# This code is contributed by shinjanpatra`

## C#

 `// C# program for the above approach` `using` `System;` `using` `System.Linq;` `using` `System.Collections.Generic;`   `class` `GFG {`   `  ``// Function to calculate the minimum cost` `  ``// required to reach the end of Line` `  ``static` `void` `minCost(``int` `N, ``int` `K, ``int` `M,` `                      ``int``[] a, ``int``[] b)` `  ``{` `    ``// Checks if possible to` `    ``// reach end or not` `    ``bool` `flag = ``true``;`   `    ``// Stores the stations and` `    ``// respective rate of fuel` `    ``Dictionary<``int``, ``int``> map = ``new` `Dictionary<``int``, ``int``>();` `    ``for` `(``int` `i = 0; i < M; i++) {` `      ``map[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) {` `      ``Console.WriteLine(``"-1"``);` `      ``return``;` `    ``}`   `    ``// Stores the station index and cost of fuel and` `    ``// litres of petrol which is being fueled` `    ``List<``int``[]> pq` `      ``= ``new` `List<``int``[]>();`     `    ``int` `cost = 0;` `    ``flag = ``false``;`   `    ``// Iterate through the entire line` `    ``for` `(``int` `i = 0; i < N; i++) {`   `      ``// Check if there is a station at current index` `      ``if` `(map.ContainsKey(i))` `        ``pq.Add(``new` `int``[] { i, map[i], 0 });`   `      ``pq = pq.OrderBy(c => c).ToList();` `      ``// Remove all the stations where` `      ``// fuel cannot be pumped` `      ``while` `(pq.Count > 0 && pq == K)` `        ``pq.RemoveAt(0);`   `      ``// If there is no station left to fill fuel` `      ``// in tank, it is not possible to reach end` `      ``if` `(pq.Count == 0) {` `        ``flag = ``true``;` `        ``break``;` `      ``}`   `      ``// Stores the best station` `      ``// visited so far` `      ``int``[] best_bunk = pq;`   `      ``// Pump fuel from the best station` `      ``cost += best_bunk;`   `      ``// Update the count of litres` `      ``// taken from that station` `      ``best_bunk++;`   `      ``// Update the bunk in queue` `      ``pq.Add(best_bunk);` `    ``}` `    ``if` `(flag) {` `      ``Console.WriteLine(``"-1"``);` `      ``return``;` `    ``}`   `    ``// Print the cost` `    ``Console.WriteLine(cost);` `  ``}`   `  ``// Driver Code` `  ``public` `static` `void` `Main(``string``[] args)` `  ``{` `    `  `    ``// Given value of N, K & M` `    ``int` `N = 10, K = 3, M = 4;`   `    ``// Given arrays` `    ``int``[] a = { 0, 1, 4, 6 };` `    ``int``[] b = { 5, 2, 2, 4 };`   `    ``// Function call to calculate minimum` `    ``// cost to reach end of the line` `    ``minCost(N, K, M, a, b);` `  ``}` `}`   `// This code is contributed by phasing17.`

## Javascript

 ``

Output:

`-1`

Time Complexity: O(N * logN)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up