|
| 1 | +""" |
| 2 | +## Questions |
| 3 | +
|
| 4 | +### 1029. [Two City Scheduling](https://leetcode.com/problems/two-city-scheduling/) |
| 5 | +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], |
| 6 | +and the cost of flying the i-th person to city B is costs[i][1]. |
| 7 | +
|
| 8 | +Return the minimum cost to fly every person to a city such that exactly N people arrive in each city. |
| 9 | +
|
| 10 | +Example 1: |
| 11 | +Input: [[10,20],[30,200],[400,50],[30,20]] |
| 12 | +Output: 110 |
| 13 | +Explanation: |
| 14 | +The first person goes to city A for a cost of 10. |
| 15 | +The second person goes to city A for a cost of 30. |
| 16 | +The third person goes to city B for a cost of 50. |
| 17 | +The fourth person goes to city B for a cost of 20. |
| 18 | +The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. |
| 19 | +
|
| 20 | +
|
| 21 | +Note: |
| 22 | +1 <= costs.length <= 100 |
| 23 | +It is guaranteed that costs.length is even. |
| 24 | +1 <= costs[i][0], costs[i][1] <= 1000 |
| 25 | +""" |
| 26 | + |
| 27 | +## Solutions |
| 28 | + |
| 29 | + |
| 30 | +class Solution: |
| 31 | + def lastStoneWeight(self, stones: List[int]) -> int: |
| 32 | + """Slow using sort each time""" |
| 33 | + if len(stones) <= 1: |
| 34 | + return stones[0] if len(stones) == 1 else None |
| 35 | + temp = sorted(stones, reverse=True) |
| 36 | + while len(temp) > 2: |
| 37 | + new_weight = abs(temp[0] - temp[1]) |
| 38 | + temp = sorted(temp[2:] + [new_weight], reverse=True) |
| 39 | + return abs(temp[0] - temp[1]) |
| 40 | + |
| 41 | + |
| 42 | +# Runtime: 32 ms, faster than 49.02% of Python3 online submissions |
| 43 | +# Memory Usage: 13.9 MB, less than 100.00% of Python3 online submissions |
| 44 | + |
| 45 | + |
| 46 | +# Solution |
| 47 | + |
| 48 | + |
| 49 | +class Solution: |
| 50 | + def twoCitySchedCost(self, costs: List[List[int]]) -> int: |
| 51 | + costA = [i for i, j in costs] |
| 52 | + diff = [j - i for i, j in costs] |
| 53 | + return sum(costA) + sum(sorted(diff)[: len(costs) // 2]) |
| 54 | + |
| 55 | + |
| 56 | +# Runtime: 36 ms, faster than 90.00% of Python3 online submissions |
| 57 | +# Memory Usage: 13.8 MB, less than 7.69% of Python3 online submissions |
0 commit comments