The intuitive thing to do is to sum up the array ranges to calculate P of 1..N but that is inefficient.
Observations:
p0 = | (A[0]) - (A[1] + A[2]) |
p1 = | (A[0] + A[1]) - (A[2]) |
If we abstract a bit then we can put the sums into two sets. The left set can be sum1 and the right set can be sum2. For each p we essentially add on to set 1 and subtract from set2 the same number. This saves you from having to sum the array ranges more than you need to.
#solution in Python
import sys
def solution(A):
sum1 = 0
sum2 = sum(A)
diff = sys.maxint
for i in range(0, len(A) -1):
sum1 += A[i]
sum2 -= A[i]
_diff = abs(sum1 - sum2)
if (diff > _diff):
diff = _diff
return diff
https://codility.com/demo/results/demo73W5DE-WZP/
No comments:
Post a Comment