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

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

Last updated

Was this helpful?