-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathGasStation.java
More file actions
40 lines (38 loc) · 1.21 KB
/
GasStation.java
File metadata and controls
40 lines (38 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
Need to find out, if a vehicle would be able to travel with the amount of fuel
**/
public class GasStation {
// DO NOT MODIFY THE ARGUMENTS WITH "final" PREFIX. IT IS READ ONLY
public int canCompleteCircuit(final int[] A, final int[] B) {
for(int i=0; i<A.length; i++)
{
int amountOfGas = 0;
int gasNeeded = 0;
int length = 0;
int j = i;
// As we are being greedy hence, we will return the first index which satisfies our need
while(length != B.length)
{
if(j >= B.length)
{
j = j%B.length;
}
//Adding gas from each station & adding it in amountOfGas & check for each gas pump
amountOfGas+=A[j];
gasNeeded+=B[j];
if(amountOfGas < gasNeeded)
{
break;
}
j++;
length++;
}
// Checks if amountOfGas was more than gasNeeded at the end of the loop.
if(amountOfGas >= gasNeeded)
{
return i;
}
}
return -1;
}
}