How to calculate n(n+1)/2 for summation of two patterns?

时间:2016-07-11 20:16:10

标签: arrays math sequence combinatorics

Suppose I have an array with range till n, say 11, that is,

U = 1 2 3 4 5 6 7 8 9 10 11

Now, I have an array-A (a sub-array of U):

1 3 4 9

and a array-B(another sub-array of U with nothing in common with A):

2 5 6 10

Note that all these 3 sets are sorted.

I have to calculate n(n+1)/2 for every (a[i+1]-a[i]-1) where i is the index of the array and a is the generalized array.

Also consider corner cases from both ends. They are to subtract 1 from first digit and then calculate n(n+1)/2 and to subtract last digit from 11 and then calculate n(n+1)/2.

For eg. For set A : We get (3-1-1)* + (4-3-1)* + (9-4-1)* + Corner Cases Here corner cases: (1-0)* + (11-9)*

x* means x(x+1)/2

Similarly for set B : We have (5-2-1)* + (6-5-1)* + (10-6-1)* + (2-1)* + (11-10)*

Now I have to calculate solution for (A U B) using set A and Set B in O(1) complexity. Is there a way to do this?

For O(N) complexity, I have just merge the two arrays and apply the above formula.

A U B : 1,2,3,4,5,6,9,10

Therefore solution = (9-6-1)*+ (11-10)*

1 个答案:

答案 0 :(得分:0)

也许你可以使用伸缩总和 (here's an exemple)。 我考虑一下,因为在每个循环(数组的每个索引)中,你减去你在前一个循环中添加的数字:

u[2] - u[1] - 1 + u[3] - u[2] - 1 + u[4] - u[3] - 1 + ... + u[n] - u[n-1]- 1 

给你:

- u[1] - 1-...-1 + u[n]
= u[n] - n - u[1]

此外,A和B没有任何共同之处,原因如下:

n = lenght(A) + length (B)

另外,因为您订购了数字:

u[1] = min ( A[1] , B[1] )
u[n] = max ( A[length[A]] , B[length[B]] )

所以我们拥有它:

Solution = max ( A[length[A]] , B[length[B]] ) - lenght(A) - length (B) - min ( A[1] , B[1] )

我希望我帮助你解决这个问题。 (对不起,如果我在英语中犯了一些错误)。