#1029. Two City Scheduling
There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1].
Return the minimum cost to fly every person to a city such that exactly N people arrive in each city.
这道题是一个贪心算法的问题。思路是让去A地花钱少的人去A地,去B地花钱少的人去B地。然后如果去A,B地的人不为N,就用去A去B差价少的人补。
/**
* @param {number[][]} costs
* @return {number}
*/
var twoCitySchedCost = function(costs) {
let N = costs.length/2;
let ans=0, AArr = [], BArr = [];
for(let i=0;i<costs.length;i++) {
if(costs[i][0]<costs[i][1]) {
ans = ans + costs[i][0];
BArr.push(costs[i][1] - costs[i][0]);
}
else {
ans = ans + costs[i][1];
AArr.push(costs[i][0] - costs[i][1]);
}
}
if(AArr.length<BArr.length) {
BArr.sort((a,b) => a-b);
for(let j=0;j<BArr.length-N;j++) {
ans = ans+BArr[j];
}
}
else if(AArr.length>BArr.length) {
AArr.sort((a,b) => a-b);
for(let j=0;j<AArr.length-N;j++) {
ans = ans+AArr[j];
}
}
return ans;
};