-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathGasStations.java
76 lines (64 loc) · 1.57 KB
/
GasStations.java
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
import java.util.Arrays;
import java.util.LinkedList;
public class GasStations {
static final int LIMIT = 1000000000;
public int solution(int[] D, int[] P, int T) {
for (int distance : D) {
if (distance > T) {
return -1;
}
}
LinkedList<Station> stations = new LinkedList<Station>();
int[] prices = Arrays.copyOf(P, P.length + 1);
stations.addLast(new Station(0));
long cost = 0;
for (int i = 0; i < D.length; i++) {
int distance = D[i];
while (distance > 0) {
Station head = stations.getFirst();
int delta = Math.min(distance, T - head.getFuel());
distance -= delta;
head.refill += delta;
if (head.getFuel() == T) {
cost += getCost(prices, head);
if (cost > LIMIT) {
return -2;
}
stations.removeFirst();
if (!stations.isEmpty()) {
stations.getFirst().base += getEarn(D, head);
}
}
}
Station added = new Station(i + 1);
while (!stations.isEmpty()
&& prices[stations.getLast().index] >= prices[i + 1]) {
Station tail = stations.removeLast();
cost += getCost(prices, tail);
if (cost > LIMIT) {
return -2;
}
added.base += getEarn(D, tail);
}
stations.addLast(added);
}
return (int) cost;
}
long getCost(int[] prices, Station station) {
return (long) prices[station.index] * station.refill;
}
int getEarn(int[] distances, Station station) {
return station.getFuel() - distances[station.index];
}
}
class Station {
int index;
int base;
int refill;
Station(int index) {
this.index = index;
}
int getFuel() {
return base + refill;
}
}