|
| 1 | +package p25xx |
| 2 | + |
| 3 | +import util.expect |
| 4 | +import java.util.* |
| 5 | + |
| 6 | +fun main() { |
| 7 | + class Solution { |
| 8 | + fun minCost(basket1: IntArray, basket2: IntArray): Long { |
| 9 | + val totalCounts = hashMapOf<Int, Int>() |
| 10 | + val basket1Counts = hashMapOf<Int, Int>() |
| 11 | + |
| 12 | + var min = Int.MAX_VALUE |
| 13 | + basket1.forEach { |
| 14 | + totalCounts[it] = (totalCounts[it] ?: 0) + 1 |
| 15 | + basket1Counts[it] = (basket1Counts[it] ?: 0) + 1 |
| 16 | + min = minOf(min, it) |
| 17 | + } |
| 18 | + basket2.forEach { |
| 19 | + totalCounts[it] = (totalCounts[it] ?: 0) + 1 |
| 20 | + min = minOf(min, it) |
| 21 | + } |
| 22 | + min *= 2 |
| 23 | + |
| 24 | + var result = 0L |
| 25 | + |
| 26 | + val queue1 = PriorityQueue<Int>() |
| 27 | + val queue2 = PriorityQueue<Int>(compareByDescending { it }) |
| 28 | + |
| 29 | + totalCounts.forEach { (key, count) -> |
| 30 | + if (count % 2 == 1) { |
| 31 | + return -1 |
| 32 | + } |
| 33 | + |
| 34 | + val target = count / 2 |
| 35 | + val b1 = basket1Counts[key] ?: 0 |
| 36 | + |
| 37 | + repeat(target - b1) { |
| 38 | + queue1.add(key) |
| 39 | + } |
| 40 | + repeat(b1 - target) { |
| 41 | + queue2.add(key) |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + while (queue1.isNotEmpty()) { |
| 46 | + result += minOf(queue1.poll(), queue2.poll(), min) |
| 47 | + } |
| 48 | + |
| 49 | + return result |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + expect { |
| 54 | + Solution().minCost( |
| 55 | + intArrayOf(4, 2, 2, 2), intArrayOf(1, 4, 1, 2) |
| 56 | + ) |
| 57 | + } |
| 58 | +} |
0 commit comments