-
Notifications
You must be signed in to change notification settings - Fork 0
/
Two city scheduling
43 lines (40 loc) · 1.33 KB
/
Two city scheduling
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
Input: [[10,20],[30,200],[400,50],[30,20]]
Output: 110
Explanation:
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
Code:
var twoCitySchedCost = function(costs) {
//Here we are sorting based on the absolute difference between 0 and 1st elemet
//this extra line compared to previous one
costs.sort((a,b) =>Math.abs(b[0]-b[1])-Math.abs(a[0]-a[1]));
let minCost = 0;
let countA = 0;
let countB = 0;
for(let i=0;i<costs.length;i++){
if(costs[i][0] <costs[i][1]){
if(countA <costs.length/2){
countA++;
minCost += costs[i][0];
}
else{
countB++;
minCost += costs[i][1];
}
}else{
if(countB <costs.length/2){
countB++;
minCost +=costs[i][1];
}
else{
countA++;
minCost += costs[i][0];
}
}
}
return minCost;
};
Status: Couldn't solve, found question ambiguous. Switched to javascript because comparator class here is much simpler.