You can do better than brute force. The brute force will be O (A Β· n), where A is the minimum acceptable value for a that we are looking for.
The approach described below uses min-heap and achieves O (n Β· log (n) + A Β· log (n)).
First, note that replacing a with the value of the form (p [i] - s [i]) + k * p [i] leads to a reminder equal to zero in i th for any positive integer k. Thus, the numbers of this form are not valid for the values ββ(the solution we are looking for is different from all).
The proposed algorithm is an effective way to generate numbers of this form (for all i and k), that is, invalid values ββfor a, in ascending order . As soon as the current value differs from the previous one by more than 1, this means that there is a valid intermediate.
The pseudocode is described below.
1. construct a min-heap from all the following pairs (p[i] - s[i], p[i]), where the heap comparator is based on the first element of the pairs. 2. a0 = -1; maxA = lcm(p[i]) 3. Repeat 3a. Retrieve and remove the root of the heap, (a, p[i]). 3b. If a - a0 > 1 then the result is a0 + 1. Exit. 3c. if a is at least maxA, then no solution exists. Exit. 3d. Insert into the heap the value (a + p[i], p[i]). 3e. a0 = a
Note: it is possible that such a does not exist. If the real a is not found below LCM (p [1], p [2], ... p [n]), then the absence of real a is guaranteed.
An example is shown below. of how this algorithm works.
Consider the following pairs (p, s): {(2, 1), (5, 3)}.
The first pair indicates that a should avoid values ββsuch as 1, 3, 5, 7, ..., while the second pair indicates that we should avoid values ββsuch as 2, 7, 12, 17, ....
The initial mini-heap contains the first element of each sequence (step 1 of the pseudocode) - in bold below:
1 , 3, 5, 7, ...
2 , 7, 12, 17, ...
We extract and remove the heap head, i.e. the minimum value among two bold, and this is 1 . We add the next element from this sequence to the heap, so the heap now contains elements 2 and 3:
1, 3 , 5, 7, ...
2 , 7, 12, 17, ...
We again extract the heap head, this time it contains the value 2 and adds the next element of this sequence to the heap:
1, 3 , 5, 7, ...
2, 7 , 12, 17, ...
The algorithm continues, we again select the value 3 and add 5 to the heap:
1, 3, 5 , 7, ...
2, 7 , 12, 17, ...
Finally, now we get the value 5 . At this stage, we understand that the value 4 is not among the invalid values ββfor a, so this is the solution we are looking for.