Find the value of max(f(x)) – min(f(x)) for a given F(x)
Given two sequences of N integers consisting of both positive and negative integers, inclusive of 0 (sequence A and sequence B). Then there will be Q queries. In each, you will be given two integers l and r (r>=l). Let’s define a function:
The task is to print the value of Max(f(x, y)) – Min(f(x, y)) for each query.
Input: N = 5, Q = 2 A = 0 7 3 4 5 B = 0 3 1 2 3 l = 1, r = 1 l = 1, r = 3 Output: 0 917448
Input: N = 5, Q = 2 A = 0 -8 3 4 -9 B = 0 -3 -5 2 3 l = 1, r = 1 l = 1, r = 3 Output: 0 851916
Approach: If we clearly see, the function only depends on the value of x and y which can be easily calculated by seeing the nature of the summation of the individual arrays. First, we precalculate the prefix sum of both the arrays, and then we just see the nature of the summations. And always the value of x and y will either be 32766 or -32766 as we are taking the modulo of them.
Below is the implementation of the above approach:
- Time Complexity: O(n) // only one traversal of the array is needed.\
- Auxiliary Complexity: O(q*2)