Maximum value of modulus expression
You are given two arrays ‘ARR1’ and ‘ARR2’ having equal length ‘N’. Your task is to return the maximum value of the expression:
|ARR1[ i ] - ARR1[ j ]| + |ARR2[ i ] - ARR2[ j ]| + |i - j|, where 0 <= i, j < n and ‘|A|’ represents the absolute (i.e., non-negative) value of ‘A’.
Example:
n = 4, ARR1 = {1, 2, 3, 4}, ARR2 = {-1, 3, 4, 2}
The maximum value of the expression is obtained when indexes ‘i = 0’ and ‘j = 3’. After evaluating the expression, we get:
|ARR1[0] - ARR2[3]| + |ARR2[0] - ARR2[3]| + |0 - 3| => |1 - 4| + |-1 - 2| + |-3| => |-3| + |-3| + 3 => 9
So the answer is 9.
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases.
The first line of each test case contains a single integer ‘N’ denoting the length of array ‘ARR1’ and ‘ARR2’.
The second line of each test case contains 'N' space-separated integers denoting the elements of array 'ARR1'.
The third line of each test case contains 'N' space-separated integers denoting the elements of array 'ARR2'.
Output format:
For each test case, print a single line containing a single integer denoting the maximum value of the given expression.
The output of each test case will be printed in a separate line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 100
1 <= N <= 1000
-10 ^ 6 <= ARR1[ i ], ARR2[ i ] <= 10 ^ 6
Where ‘T’ is the total number of test cases, ‘N’ denotes the length of arrays 'ARR1' & 'ARR2', and ‘ARR1[i]’ & ‘ARR2[i]’ represents the elements in the respective arrays
Time limit: 1 sec.
CodingNinjas
author
2y
first we can easily solve using two for loops
then we can optimize by removing mod operations, doing simple maths
CodingNinjas
author
2y
Brute force
We can use two nested loops to iterate through all the possible ‘N * N’ pairs of indexes ‘i’ and ‘j’ to obtain the given expression’s maximum value.
- Initialize variable ‘MAXEXP = INT_MIN’ a...read more
CodingNinjas
author
2y
Expand the modulus function
Consider the following properties of the modulus function:
- |A| = max(-A, A).
- |A| + |B| = max(A + B, A - B, -A + B, -A - B).
- |A| + |B| + |C| = max(A + B + C, A - B + C, -A + B +...read more
Add answer anonymously...
Top Delhivery Software Developer Intern interview questions & answers
Popular interview questions of Software Developer Intern
>
Delhivery Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app