Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8c4fae0

Browse files
1
1 parent e97a198 commit 8c4fae0

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

‎src/main/kotlin/p25xx/Problem2561.kt

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /