Lesson counting

I am studying the Codility Counting Lesson ( https://codility.com/media/train/2-CountingElements.pdf ) and I need help to figure out the quickest solution.

I am wondering why the difference is divisible by 2 in line 8 d //= 2? Isn't the difference enough to find the elements that we can swap between arrays?

Problem:

You are given integer m( 1 < m < 1000000) and two non-empty, the zero-indexed arrays Aand Bof nintegers a0, a1, ..., an−1, and b0, b1, ..., bn−1respectively ( 0 < ai, bi < m). The goal is to check if there is a swap operation that can be performed on these arrays in such a way that the sum of the elements in the array Ais equal to the sum of the elements in the array Bafter the exchange. From we mean the selection of one element from the array Aand one element from the array Band exchanging them.

Decision:

 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
+4
source share
2 answers

A[i] B[j] B[j]-A[i] sum(A) sum(B); B[j]-A[i].

, ( - , ! -), .

, counting, , Python - " ", . https://docs.python.org/2/library/collections.html#collections.Counter Python 2 https://docs.python.org/3/library/collections.html#collections.Counter Python 3.

+7

Ea = a0 + a1 + .. + a(n-1). Eb = b0 + b1 + .. + b(n-1). ai bj : Ea - ai + bj, Eb + ai - bj. , , Ea - ai + bj = Eb + ai - bj d = bj - ai. : Ea + d = Eb - d, 2d = Eb - Ea d = (Eb - Ea)/2. , (Eb - Ea) , . comment Alex Martelli

bj ai, bj - ai = d.

+2

Source: https://habr.com/ru/post/1568459/


All Articles