def solution(arr):
total = sum(arr)
mem = [0] * len(arr)
mem[0] = total
for i, j in enumerate(arr[1:], start=1):
mem[i] = mem[i-1] - j
res = 0
for i, j in enumerate(arr):
if j != 0:
continue
res += mem[i]
return res
#Challenge
Source | Language | Runtime |
---|---|---|
codility | python |
A non-empty array
Array
For example with an array A:
A[0] = 0
A[1] = 1
A[2] = 0
A[3] = 1
A[4] = 1
We have five pairs of passing cars:
#Solution
The thing to notice about this problem is that for each zero we encounter, we add all the ones we encounter in the array after that zero.
In the previous example, there's a zero at index
The best way to approach this problem is to keep track of how many cars are ahead
of each car at each index. We could do this using a nested loop, running in mem
. Beginning
with the sum of all values in the array, each index subtracts the corresponding value in A
from the index before it.
For the example above this leaves us with:
mem[0] = 3
mem[1] = 2
mem[2] = 2
mem[3] = 1
mem[4] = 0
Now we can just iterate from the start of the array to the end, incrementing a counter by the
value of mem[i]
for each