如果i去A地花费10,去B地花费100
j去A地花费10,去B地花费110
那么j优先去A地
这是因为j去A比j去B节省了100
而i去A之比i去B节省了90
Intuition
How much money can we save if we fly a person to A vs. B? To minimize the total cost, we should fly the person with the maximum saving to A, and with the minimum - to B.
Example: [30, 100], [40, 90], [50, 50], [70, 50].
Savings: 70, 50, 0, -20.
Obviously, first person should fly to A, and the last - to B.
Solution
We sort the array by the difference between costs for A and B. Then, we fly first N people to A, and the rest - to B.
int twoCitySchedCost(vector<vector<int>>& cs, int res = 0) {
sort(begin(cs), end(cs), [](vector<int> &v1, vector<int> &v2) {
return (v1[0] - v1[1] < v2[0] - v2[1]);
});
for (auto i = 0; i < cs.size() / 2; ++i) {
res += cs[i][0] + cs[i + cs.size() / 2][1];
}
return res;
}
Complexity Analysis
Runtime: O(n log n). We sort the array then go through it once.
Memory: O(1). We sort the array in-place.
class Solution {
public int twoCitySchedCost(int[][] costs) {
// 我们进可能让costs[i][1]-costs[i][0]大的去A
Arrays.sort(costs, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
// TODO Auto-generated method stub
return o2[1] - o2[0] - o1[1] + o1[0];
}
});
int ans = 0;
int len = costs.length;
for (int i = 0; i < len / 2; ++i)
ans += costs[i][0] + costs[len / 2 + i][1];
return ans;
}
}