...

/

Gas Stations

Gas Stations

Try to solve the Gas Station problem.

Statement

There are nn gas stations along a circular route, where the amount of gas at the ithi^{th} station is gas[i].

We have a car with an unlimited gas tank, and it costs cost[i] of gas to travel from the ithi^{th} station to the next (i+1)th(i+1)^{th} station. We begin the journey with an empty tank at one of the gas stations.

Find the index of the gas station in the integer array gas such that if we start from that index we may return to the same index by traversing through all the elements, collecting gas[i] and consuming cost[i].

  • If it is not possible, return -1.

  • If there exists such index, it is guaranteed to be unique.

Constraints:

  • gas.length ==== cost.length
  • 1 \leq gas.length, cost.length 103\leq 10^3
  • 0 \leq gas[i], cost[i] 103\leq 10^3

Examples

canvasAnimation-image
1 / 3

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Gas Stations

1.

What will the output be if the following gas and cost arrays are provided as input?

gas = [3, 1, 1]

cost = [1, 2, 2]

A.

0

B.

1

C.

2

D.

-1


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4

Try it yourself

Implement your solution in main.cpp in the following coding playground.

C++
usercode > main.cpp
#include <iostream>
#include <vector>
int GasStationJourney(vector<int> gas, vector<int> cost)
{
// Replace this placeholder return statement with your code
return -1;
}
Gas Station

Access this course and 1200+ top-rated courses and projects.