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