1029 Two City Scheduling

1029 Two City Scheduling

Techniques Used

  • Greedy
  • Sorting

Approach

  • Sorting based on either costA or costB is not going to be enough, we also need to account for the difference between the two costs, and use a metric that can take that into account, and hence we used the difference of two costs as a metric to sort by.
  • Once you have sorted in that manner, then we just need to
    • pick the first n elements and send those people to city A.
    • pick the last n elements and send those people to city B.

Complexity:

  • Time Complexity: O(NlogN) - N is the number of elements in the costs array.
  • Space Complexity: O(1) No extra space was used.

Code:


class Solution {
    public int twoCitySchedCost(int[][] costs) {


        Arrays.sort(costs, (a, b) -> {
                    return (a[0] - a[1]) - (b[0] - b[1]);
        });


        int total_cost = 0;

        for(int i = 0; i < costs.length/2; i++){
            total_cost += costs[i][0];
        }


        for(int i = costs.length/2; i < costs.length; i++){
            total_cost += costs[i][1];
        }
        return total_cost;
    }
}