当前位置:首页|资讯

GFG 169 Minimize Cost

作者:您是打尖儿还是住店呢发布时间:2024-10-16

You are given two integer arrays a and b, each of length n. You have to make the two arrays

identical (a should be a permutation of b) by performing a series of swap operations between

their elements.


1. Choose an index i (1 ≤ i ≤ n) from array a and index j (1 ≤ j ≤ n) from array b.

2. Swap a and b with the cost as min(a , b ).


Your task is to minimize the total cost of all swaps needed to make the arrays identical. If it is

impossible to make the arrays identical, return -1.


Example 1:


Input:

n = 4

a = [1, 2, 2, 2]

b = [1, 2, 4, 4]

Output: 2

Explanation:

To make a and b identical, swap the element a = 2 with the element b = 4.

The cost of this swap is min(2, 4) = 2. After the swap, a becomes [1, 2, 2, 4] and b

becomes [1, 2, 4, 2], making the arrays identical with a total cost of 2.


Example 2:


Input:

n = 2

a = [2, 4]

b = [2, 3]

Output: -1

Explanation: There is no possible swaps to make both arrays identical.


Your Task:

The task is to complete the function minCost() which takes one integer n and two arrays a and b

Constraints:

1 ≤ n ≤ 10

1 ≤ a[i],b[i] ≤ 10

------

交换2个数组的元素,使得a数组跟b数组最后同构即可,就是记录两个数组元素的数量,差值必须是偶数,然后将差值放到list中,排序,用前一半即可,因为交换的成本是用的较小值。这一点还是有点不太理解。



Copyright © 2024 aigcdaily.cn  北京智识时代科技有限公司  版权所有  京ICP备2023006237号-1