I am analyzing counting example in python presented by Codility
I don't understand the logic used in the last loop (5 last rows) of this algorithm.
Can anybody help please?
The problem:
You are given an integer
m(1 < m < 1000000) and two non-empty, zero-indexed arraysAandBofnintegers,a0,a1, ... ,an−1andb0,b1, ... ,bn−1respectively (0 < ai,bi < m). The goal is to check whether there is a swap operation which can be performed on these arrays in such a way that the sum of elements in arrayAequals the sum of elements in arrayBafter the swap. By swap operation we mean picking one element from arrayAand one element from arrayBand exchanging them.
The solution:
def counting(A, m):
n = len(A)
count = [0] * (m + 1)
for k in xrange(n):
count[A[k]] += 1
return count
def fast_solution(A, B, m):
n = len(A)
sum_a = sum(A)
sum_b = sum(B)
d = sum_b - sum_a
if d % 2 == 1:
return False
d //= 2
count = counting(A, m)
for i in xrange(n):
if 0 <= B[i] - d and B[i] - d <= m and count[B[i] - d] > 0:
return True
return False