-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
58 lines (46 loc) · 1.64 KB
/
Solution.java
File metadata and controls
58 lines (46 loc) · 1.64 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
import java.util.Queue;
import java.util.LinkedList;
class Truck{
int weight;
int inTime;
public Truck(int weight, int inTime){
this.weight = weight;
this.inTime = inTime;
}
}
public class Solution {
public static void main(String[] args){
int bridge_length = 2;
int weight = 10;
int[] truck_weights = {7,4,5,6};
int answer = solution(bridge_length, weight, truck_weights);
System.out.println(answer);
}
public static int solution(int bridge_length, int weight, int[] truck_weights) {
Queue<Truck> waiting_trucks = new LinkedList<Truck>();
Queue<Truck> trucks_on_bridge = new LinkedList<Truck>();
for(int truck_weight : truck_weights){
waiting_trucks.add(new Truck(truck_weight, 0));
}
int time = 0;
int totalWeight = 0;
while(!waiting_trucks.isEmpty() || !trucks_on_bridge.isEmpty()){
time++;
if(!trucks_on_bridge.isEmpty()){
Truck t = trucks_on_bridge.peek();
if(time - t.inTime >= bridge_length){
totalWeight -= t.weight;
trucks_on_bridge.poll();
}
}
if(!waiting_trucks.isEmpty()){
if(totalWeight + waiting_trucks.peek().weight <= weight){
Truck t = waiting_trucks.poll();
totalWeight += t.weight;
trucks_on_bridge.add(new Truck(t.weight, time));
}
}
}
return time;
}
}