-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGasStation.java
More file actions
89 lines (77 loc) · 2.79 KB
/
Copy pathGasStation.java
File metadata and controls
89 lines (77 loc) · 2.79 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.leetcode.year_2020.Greedy;
/**
* https://leetcode.com/problems/gas-station/
*
* @author neeraj on 05/07/20
* Copyright (c) 2019, data-structures.
* All rights reserved.
*/
public class GasStation {
public static void main(String[] args) {
System.out.println(canCompleteCircuit(
new int[]{1, 2, 3, 4, 5},
new int[]{3, 4, 5, 1, 2}));
System.out.println(canCompleteCircuitON2(
new int[]{1, 2, 3, 4, 5},
new int[]{3, 4, 5, 1, 2}));
System.out.println(canCompleteCircuit(
new int[]{2, 3, 4},
new int[]{3, 4, 3}));
System.out.println(canCompleteCircuitON2(
new int[]{2, 3, 4},
new int[]{3, 4, 3}));
}
public static int canCompleteCircuitON2(int[] gas, int[] cost) {
for (int i = 0; i < gas.length; i++) {
if (gas[i] < cost[i]) {
continue;
}
int j = (i + 1) % gas.length;
int gasAtCurrentStation = gas[i];
int costForReachingNextStation = cost[i];
int gasAfterReachingNextStation = gasAtCurrentStation - costForReachingNextStation + gas[j];
while (i != j) {
if (gasAfterReachingNextStation < cost[j]) {
break;
}
costForReachingNextStation = cost[j];
j = (j + 1) % gas.length;
gasAfterReachingNextStation = gasAfterReachingNextStation - costForReachingNextStation + gas[j];
}
if (i == j) {
return i;
}
}
return -1;
}
public static int canCompleteCircuit(int[] gas, int[] cost) {
/**
* Intuition :
* Two Pass
* 1) if the total gas >= total cost, then we can definitely reach all Cities
* 2) Now if we can reach to any petrol pump. we will start from 0th petrol city,
* and keep our tankStatus = tank + (cost[i] - gas[i]).
* Whenever our tank reaches negative state means, we started from a wrong city
* and we shouldn't start from the city before the current city. So we will start from currentCity + 1;
*/
// First Pass
int fuelTank = 0;
for (int i = 0; i < gas.length; i++) {
fuelTank += gas[i] - cost[i];
}
if (fuelTank < 0) { // We can't reach to all cities and make circular tour.
return -1;
}
// Second Pass
fuelTank = 0;
int startStation = 0;
for (int i = 0; i < gas.length; i++) {
fuelTank += gas[i] - cost[i];
if (fuelTank < 0) {
fuelTank = 0;
startStation = i + 1;
}
}
return startStation;
}
}