1029. Two City Scheduling
https://leetcode.com/problems/two-city-scheduling/
use greedy
因為透過觀察,
Input: [[10,20],[30,200],[400,50],[30,20]]cost[0] - cost[1] 的話, 會是 -10, -170, 350, 10
代表越小的結果, 應該派去 A, 會最好,
[[10,20],[30,200] 會選擇前者本題說要一半的人去 A 一半的去 B, 所以透過排序 cost[0] - cost[1] , 由小到大
前一半的人去 A, 後一半的人去 B , 會是最佳解!
O(nlogn), O(1)
class Solution {
public int twoCitySchedCost(int[][] costs) {
Arrays.sort(costs, (a, b) -> {
return (a[0] - a[1]) - (b[0] - b[1]);
});
int res = 0;
for (int i = 0; i < costs.length; i++) {
if (i < costs.length/2) {
res += costs[i][0];
} else {
res += costs[i][1];
}
}
return res;
}
}dp 解
dp[i][j] represents the cost when considering first (i + j) people in which i people assigned to city A and j people assigned to city B.
O(n^2), O(n^2), N = costs.length / 2
Previous874. Walking Robot SimulationNext1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
Last updated
Was this helpful?