-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1029-two-city-scheduling.js
More file actions
34 lines (30 loc) · 956 Bytes
/
1029-two-city-scheduling.js
File metadata and controls
34 lines (30 loc) · 956 Bytes
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
/**
* Two City Scheduling
* Time Complexity: O(N log N)
* Space Complexity: O(N)
*/
var twoCitySchedCost = function (costs) {
const totalTravelers = costs.length;
const travelersPerCity = totalTravelers / 2;
costs.sort((firstPersonData, secondPersonData) => {
const differenceForFirst = firstPersonData[0] - firstPersonData[1];
const differenceForSecond = secondPersonData[0] - secondPersonData[1];
return differenceForFirst - differenceForSecond;
});
let accumulatedCost = 0;
for (
let currentTravelerIndex = 0;
currentTravelerIndex < totalTravelers;
currentTravelerIndex++
) {
const currentTravelerCosts = costs[currentTravelerIndex];
const cityACost = currentTravelerCosts[0];
const cityBCost = currentTravelerCosts[1];
if (currentTravelerIndex < travelersPerCity) {
accumulatedCost += cityACost;
} else {
accumulatedCost += cityBCost;
}
}
return accumulatedCost;
};