![]() |
VOOZH | about |
Given two sorted arrays A and B of size N and M respectively, the task is to find the value V, which is the summation of (A[j] - A[i]) for all pairs of i and j such that (j - i) is present in array B.
Examples:
Input: N = 4, M = 2, A[] = {1, 2, 3, 4}, B[] = {1, 3}
Output: 6
Explanation: Valid pairs of (i, j) are (1, 2), (2, 3), (3, 4), (1, 4). So the answer will be 2 - 1 + 3 - 2 + 4 - 3 + 4 - 1 = 6Input: N = 3, M = 3, A[] = (2, 3, 5}, B[] = (1, 2, 3}
Output: 6
Approach: To solve the problem follow the below steps:
- Let's find the answer for one value in the B array. Later we can sum it up to get the end result.
- Suppose there is a value 'x' in the B array. So the result will be equal to
- result = (A[x] - A[0]) + (A[x+1] - A[1]) + (A[x+2] - A[2]) ....... and so on till the end of the array.
- If we re-arrange the equation, then we will get something like this:
- result = (A[x] + A[x+1] + A[x+2] + .... + A[n-1]) - (A[0] + A[1] + A[2] + ........A[n-x-1]).
- Which is nothing but the suffix sum of the last x elements - prefix sum of the first n-x-1 elements.
- Which will now yield the value of the single element in the array B. Now we iterate over the array B and compute the summation of all the results to get the end result.
Below are the steps to solve the above approach:
Below is the implementation of the above approach:
6
Time complexity: O(N + M)
Auxiliary Space: O(N)