#K79417. Balance Arrays with At Most One Swap
Balance Arrays with At Most One Swap
Balance Arrays with At Most One Swap
You are given two lists of integers. Your task is to determine whether it is possible to make these two lists identical by swapping at most one integer from the first list with one integer from the second list.
Two lists are considered identical if, after sorting each list, they are exactly the same. Note that if the lists are already identical (after sorting), no swap is needed. However, if the two lists have different lengths or if either list is empty, they are considered to be non‐balanceable and the answer should be False
.
Let the two lists be \( A = [a_1, a_2, \dots, a_n] \) and \( B = [b_1, b_2, \dots, b_n] \). One of the approaches is to compare the sums of the arrays. If a swap is to balance the arrays, then the difference in sums must be even. More formally, define the difference: \[ \Delta = \sum_{i=1}^{n} a_i - \sum_{i=1}^{n} b_i. \] If \( \Delta \) is even, then there exists a potential swap if for some \( b_j \) in \( B \) the number \( b_j + \Delta/2 \) exists in \( A \). If such a pair exists, you may swap these two numbers to achieve balance.
Input is provided via standard input (stdin) and output should be printed to standard output (stdout) as either True
or False
.
inputFormat
The input consists of two lines:
- The first line contains space-separated integers representing the first array.
- The second line contains space-separated integers representing the second array.
If a line is empty, it represents an empty array.
outputFormat
Output a single line to stdout which is either True
if the arrays can be balanced by swapping at most one pair of elements, or False
if they cannot.
1 2 3
1 2 3
True