-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1029-two-city-scheduling.java
More file actions
54 lines (47 loc) · 1.43 KB
/
1029-two-city-scheduling.java
File metadata and controls
54 lines (47 loc) · 1.43 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
class Solution {
class Person implements Comparable<Person>{
private int idx;
private int costA;
private int costB;
private int prefCity;
private int gap;
public Person(int idx, int costA, int costB) {
this.idx = idx;
this.costA = costA;
this.costB = costB;
this.prefCity = Math.min(costA, costB);
this.gap = Math.abs(costA - costB);
}
//sort the gaps from big to low
public int compareTo(Person o) {
return Integer.compare(o.gap, this.gap);
}
}
public int twoCitySchedCost(int[][] costs) {
PriorityQueue<Person> pq = new PriorityQueue<>();
for (int i = 0; i < costs.length; i++) {
pq.offer(new Person(i, costs[i][0], costs[i][1]));
}
int res = 0, n = costs.length / 2;
int a = 0, b = 0;
//apply greedy algorithm
while (!pq.isEmpty()) {
Person p = pq.poll();
if (b < n) {
if (p.prefCity == p.costB || a == n) {
b++;
res += p.costB;
}
else {
a++;
res += p.costA;
}
}
else {
a++;
res += p.costA;
}
}
return res;
}
}