-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrain_Bus.java
More file actions
73 lines (59 loc) · 1.98 KB
/
Train_Bus.java
File metadata and controls
73 lines (59 loc) · 1.98 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
package cp3;
public class Train_Bus {
public static void main(String[] args) {
int[] trainPrices = {5, 100, 5, 100, 5};
int[] busPrices = {100, 5, 100, 5, 100};
int n = trainPrices.length;
int switchCost = 10;
int[] dp = new int[n];
int cost = 0;
boolean onTrain = false; // Boolean used for logic control flow
if(trainPrices[0] < busPrices[0]){
cost = trainPrices[0];
onTrain = true;
}
else if(trainPrices[0] > busPrices[0]){
cost = busPrices[0];
onTrain = false;
}
else{ // trainPrices[0] == busPrices[0]
if (trainPrices[1] > busPrices[1]){
cost = busPrices[0]; // choose bus
onTrain = false;
}
else{
cost = trainPrices[0]; // choose train
onTrain = true;
}
}
dp[0] = cost;
// Process the rest of the stations
for(int i = 1; i < n; i++){
if(onTrain){
if(trainPrices[i] > busPrices[i] + switchCost){
cost += switchCost + busPrices[i];
onTrain = false;
}
else{
cost += trainPrices[i];
}
}
else{
if (busPrices[i] > trainPrices[i] + switchCost){
cost += switchCost + trainPrices[i];
onTrain = true;
}
else{
cost += busPrices[i];
}
}
dp[i] = cost;
}
for (int i = 0; i < n; i++){
int res = dp[i];
System.out.print(res + " ");
}
System.out.println();
System.out.println("Suzie Q can reach her final destination by paying " + dp[n-1]+ " dollars!");
}
}