Welcome back.
Let's now implement the solution for the two city scheduling cost problem okay.
So we are given this costs array.
And every element in this array over here is an array itself.
And it will have two elements.
Right.
So every element over here in this array will have two elements.
And the first element represents the cost to city A.
And the second element represents the cost to city B okay.
So that's given in the question.
Now the way that we are going to approach this is that we are going to sort the costs array which is
given to us, and we are going to sort it by the difference between these two costs for every element.
So let's go ahead and implement that.
Okay.
Now let's say the initial cost is set to zero.
And what we will be doing is we will be just going through the first half of elements.
So let's say it is cost dot length divided by two okay.
So for the first half of elements we will just pick city A.
So for let I is equal to zero I less than n I plus plus we're just going to say cost plus is equal to
costs I at index zero which is equivalent to sending that person to city A.
And for the remaining half we're just going to send people to city B okay.
So I is equal to n.
Let's say I less than two into n and I plus plus and cost plus is going to equal costs at index I at
index one, which is the cost for sending that person to city B and that's it.
And then we would just return costs okay.
So this is how we can solve this question.
Now let's go ahead and run this code and see if it's passing all the test cases.
And you can see that it's working.
It's passing all the test cases.
And notice we have used a greedy approach to solve this question.