algorithm - Sum of all subparts of an array of integers -
given array {1,3,5,7}
, subparts defined {1357,135,137,157,357,13,15,17,35,37,57,1,3,5,7}
. have find sum of these numbers in new array. in case sum comes out 2333. please me find solution in o(n)
. o(n^2)
solution times out.
my current attempt( @ finding pattern) is
for(i=0 len) //len length of array { for(j=0 len-i) { sum+= arr[i]*pow(10,j)*((len-i) c i)*pow(2,i) } }
in words - len-i c = (number of integers right) c weight. (combinations {from permutation , combination}) 2^i = 2 power (number of integers left)
thanks
you can solve problem simple recursive.
def f(arr): if len(arr) == 1: return (arr[0], 1) else: r = f(arr[:-1]) return (11 * r[0] + (r[1] + 1) * arr[-1], 2 * r[1] + 1)
so, how work? simple. let want compute sum of subpart of {1,3,5,7}. let assume know number of combinatiton of {1,3,5} , sum of subpart of {1,3,5} , can compute {1,3,5,7} using following formula:
sum_subpart({1,3,5,7}) = 11 * sum_subpart({1,3,5}) + number_combination({1,3,5}) * 7 + 7
this formula can derived observing. let have combination of {1,3,5}
a = [135, 13, 15, 35, 1, 3, 5]
we can create list of {1,3,5,7} by
a = [135, 13, 15, 35, 1, 3, 5] + [135 * 10 + 7, 13 * 10 + 7, 15 * 10 + 7, 35 * 10 + 7, 1 * 10 + 7, 3 * 10 + 7, 5 * 10 + 7] + [7]
Comments
Post a Comment