|
| 1 | +package com.kishan.scala.leetcode.juneChallenges |
| 2 | + |
| 3 | +/* |
| 4 | +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], |
| 5 | +and the cost of flying the i-th person to city B is costs[i][1]. |
| 6 | +Return the minimum cost to fly every person to a city such that exactly N people arrive in each city. |
| 7 | +*/ |
| 8 | + |
| 9 | +/* |
| 10 | +Input: [[10,20],[30,200],[400,50],[30,20]] |
| 11 | +Output: 110 |
| 12 | +Explanation: |
| 13 | +The first person goes to city A for a cost of 10. |
| 14 | +The second person goes to city A for a cost of 30. |
| 15 | +The third person goes to city B for a cost of 50. |
| 16 | +The fourth person goes to city B for a cost of 20. |
| 17 | +
|
| 18 | +The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. |
| 19 | +
|
| 20 | +Note: |
| 21 | + 1. 1 <= costs.length <= 100 |
| 22 | + 2. It is guaranteed that costs.length is even. |
| 23 | + 3. 1 <= costs[i][0], costs[i][1] <= 1000 |
| 24 | +*/ |
| 25 | + |
| 26 | +/* |
| 27 | +* Approach (Greedy Algorithm) |
| 28 | +* 1. Find absolute difference. |
| 29 | +* 2. Sort in descending order. |
| 30 | +* 3. Iterate and get the minimum of the city. Update the sum. |
| 31 | +* 4. Have the count of the cityA and cityB. |
| 32 | +* */ |
| 33 | + |
| 34 | + |
| 35 | +object twoCityScheduling { |
| 36 | + def main(args: Array[String]): Unit = { |
| 37 | + val costs = Array(Array(259, 770), Array(448, 54), Array(926, 667), Array(184, 139), Array(840, 118), Array(577, 469)) |
| 38 | + // val costs1 = Array(Array(10, 20), Array(30, 200), Array(400, 50), Array(30, 20)) |
| 39 | + val result = twoCitySchedCost(costs) |
| 40 | + println(result, result == 1859) |
| 41 | + } |
| 42 | + |
| 43 | + def twoCitySchedCost(costs: Array[Array[Int]]): Int = { |
| 44 | + val length = costs.length |
| 45 | + if (length % 2 != 0 && (length <= 1 && length >= 100)) { |
| 46 | + return -1 |
| 47 | + } |
| 48 | + val costsSorted: Array[Array[Int]] = costs.map(a => (a, math.abs(a(0) - a(1)))).sortBy(a => a._2)(Ordering.Int.reverse).map(_._1) |
| 49 | + var cityA: Int = 0 |
| 50 | + var cityB: Int = 0 |
| 51 | + var sum: Int = 0 |
| 52 | + for (person <- costsSorted) { |
| 53 | + val a = person(0) |
| 54 | + val b = person(1) |
| 55 | + if (a < b) { |
| 56 | + if (cityA < length / 2) { |
| 57 | + sum += a |
| 58 | + cityA += 1 |
| 59 | + } else { |
| 60 | + sum += b |
| 61 | + cityB += 1 |
| 62 | + } |
| 63 | + } else { |
| 64 | + if (cityB < length / 2) { |
| 65 | + sum += b |
| 66 | + cityB += 1 |
| 67 | + } else { |
| 68 | + sum += a |
| 69 | + cityA += 1 |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + sum |
| 74 | + } |
| 75 | + |
| 76 | + |
| 77 | +} |
0 commit comments