Created
May 21, 2023 22:31
-
-
Save optimistiks/d88038a8ac4b54205e5d6e9f999f71e9 to your computer and use it in GitHub Desktop.
Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export function twoCityScheduling(costs) { | |
| // create an array of cost differences and sort it ascending | |
| const diffs = costs.map(([costA, costB]) => costA - costB); | |
| diffs.sort((a, b) => a - b); | |
| // get a sum of all costs to city A (like we sent all people to city A) | |
| let sumA = costs.reduce((sum, [costA]) => sum + costA, 0); | |
| // since we are actually sending the second half of people (by diffs) to city B | |
| // subtract their differences (think refunds) from the sumA | |
| for (let i = diffs.length / 2; i < diffs.length; ++i) { | |
| sumA -= diffs[i]; | |
| } | |
| return sumA; | |
| } | |
| // O(n + nlogn) because of sorting, O(n + m) memory (m because of sorting). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment