Question: In the school, two lines of students, A and B, are arranged with N students in…
- User
Question:
In the school, two lines of students, A and B, are arranged with N students in each line, facing each other. The Physical Education teacher aims to make the heights of students standing across from each other equal. This can be achieved by swapping students between the two lines. Any student in one line can be swapped with any student in the other line. Each swap, regardless of the students involved, incurs a cost equal to the height of the shorter student in the swap. Rearranging students within the same line does not incur any cost. Calculate the minimum cost required to attain this goal. If it is not feasible, the result will be -1.
Function Definition:
def rearrangeStudents(arrA: List[int], arrB: List[int]) -> int: # Write your code here
arrA: List of integers representing the heights of students in line A. arrB: List of integers representing the heights of students in line B.
Returns: long - The minimal cost to rearrange the students, or -1 if not feasible.
Constraints: 1 ≤ n ≤ 2 × 10^5 1 ≤ arrA[i], arrB[i] ≤ 10^9
Sample Input:
2 arrA = [1, 2] arrB = [2, 1]
Sample Output:
0
Explanation:
After sorting the arrays, both exhibit identical heights at corresponding positions. No further operations are required.
"Solve without explanation in python with function def rearrangeStudent(arrA,arrB): "
- Assistantpython
def rearrangeStudent(arrA, arrB): from collections import Counter countA = Counter(arrA) countB = Counter(arrB) all_keys = set(countA.keys()).union(countB.keys()) # Check if total counts are even for all heights for h in all_keys: total = countA.get(h, 0) + countB.get(h, 0) if total % 2 != 0: return -1 # Determine desired counts desired = {} for h in all_keys: desired[h] = (countA.get(h, 0) + countB.get(h, 0)) // 2 list_excess_A = [] list_excess_B = [] for h in all_keys: excess = countA.get(h, 0) - desired[h] if excess > 0: list_excess_A.extend([h] * (excess // 2)) elif excess < 0: list_excess_B.extend([h] * (-excess // 2)) if len(list_excess_A) != len(list_excess_B): return -1 if not list_excess_A: return 0 m = min(min(arrA), min(arrB)) list_excess_A.sort() list_excess_B.sort(reverse=True) total_cost = 0 k = len(list_excess_A) for i in range(k): total_cost += min(list_excess_A[i], list_excess_B[i], 2 * m) return total_cost