Two City Scheduling
LeetCode Problem #1029 (Medium)
Problem Statement
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.
Testcase
Problem Explanation
A particular cost is incurred when an individual is sent to one of two cities—City A or City B for an interview. The costs are given in a two-dimensional vector where each vector inside it represents the travel cost for every person.
The first value in the vector is the cost of sending a person to City A.
The second value in the vector is the cost of sending a person to City B.
Out of the total number of people (2N), we can only send half to each city (N). We must calculate the optimum (minimum) cost that can be generated by sending people to either of the two cities.
Algorithm
Difference of Costs Approach
In this approach, we calculate the difference between sending a person to City A and sending the person to City B to see if there is a profit in sending the person to one city over another.
Since only half the people can go to each city, we sort the list of people based on this value of profit and send the first half to City A and send the second half to City B such that we gain maximum profit by doing so.
Calculate the cost of sending every person to City A and store it in a variable.
Calculate the difference between sending a person to City B instead of City A, and store it in an array.
Sort the values in the array. The smaller the difference value, the greater the profit earned by sending them to City B.
Choose the first N people from the array (the ones having lowest difference value) and send them to City B.
Add the difference of the cost of sending people to City B instead of City A to the original total cost.
Example:
Consider the input array:
Add the cost of sending each person to City A. This value is the first value in the vector.
Calculate the difference or "refund" that would be incurred if each person is sent to City B instead of City A. This can be done by subtracting the first value in the vector from the second value.
Sort the refund values in ascending order.
The smaller the value, the greater the profit gained by sending the person to City B instead of City A. Choose the first N people out of the total 2N people to send to City B as stipulated by the question.
Add these values to the originally obtained minCost to calculate the total minimum cost.
Code
Last updated
Was this helpful?