[LeetCode 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.

 

Example 1:

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.

 

Note:

  1. 1 <= costs.length <= 100
  2. It is guaranteed that costs.length is even.
  3. 1 <= costs[i][0], costs[i][1] <= 1000

 

 

 

Given the input size is pretty small,  the first thought is that we can use dynamic programming. 

Solution 1. Dynamic Programming

dp[i][j]: the min cost of people in [0, i] with j of them flying to city A. 

dp[i][j] = Math.min(dp[i - 1][j - 1] + costs[i][0],  dp[i - 1][j] + costs[i][1]);  For the current people i, he can either be flied to A or B. 

ans: dp[N * 2 - 1][N]

 

class Solution {
    public int twoCitySchedCost(int[][] costs) {        
        int[][] dp = new int[costs.length][costs.length / 2 + 1];
        for(int i = 0; i < dp.length; i++) {
            Arrays.fill(dp[i], (int)1e9);
        }
        dp[0][0] = costs[0][1];
        dp[0][1] = costs[0][0];
        
        for(int i = 1; i < dp.length; i++) {
            dp[i][0] = dp[i - 1][0] + costs[i][1];
            for(int j = 1; j <= Math.min(costs.length / 2, i + 1); j++) {
                dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1] + costs[i][0]);
                dp[i][j] = Math.min(dp[i][j], dp[i - 1][j] + costs[i][1]);
            }
        }
        return dp[dp.length - 1][costs.length / 2];
    }
}

 

 

Solution 2. Greedy 

It turns out that this problem can be solved using a greedy approach. For each person, he has to fly to one of A or B. We can think in this way: how much can we save if we fly a person to A vs B? To minimize the total cost, we need to fly persons with max saving to A, and with min saving to B. 

 

1. Sort the input costs by the savings we can get by flying person to A vs B. After this sorting, the 1st half of the costs provide more savings if we fly these persons to A.

2. Sum up the 1st half for A and 2nd half for B.

 

class Solution {
    public int twoCitySchedCost(int[][] costs) {
        Arrays.sort(costs, Comparator.comparingInt(c -> c[0] - c[1]));
        int sum = 0;
        for(int i = 0; i < costs.length / 2; i++) {
            sum += costs[i][0];
        }
        for(int i = costs.length / 2; i < costs.length; i++) {
            sum += costs[i][1];
        }
        return sum;
    }
}

 

posted @ 2020-06-04 02:24  Review->Improve  阅读(239)  评论(0编辑  收藏  举报