https://www.geeksforgeeks.org/maximum-value-arri-arrj-j/
Given a array of N positive integers. The task is to find maximum value of |arr[i] – arr[j]| + |i – j|, where 0 <= i, j <= N – 1 and arr[i], arr[j] belong to the array.
Examples:
Input : N = 4, arr[] = { 1, 2, 3, 1 } Output : 4 Choose i = 0 and j = 4
First of all lets make four equations by removing the absolute value signs (“|”). Following 4 equations will be formed, and we need to find the maximum value of these equation and that will be our answer.
- arr[i] – arr[j] + i – j = (arr[i] + i) – (arr[j] + j)
- arr[i] – arr[j] – i + j = (arr[i] – i) – (arr[j] – j)
- -arr[i] + arr[j] + i – j = -(arr[i] – i) + (arr[j] – j)
- -arr[i] + arr[j] – i + j = -(arr[i] + i) + (arr[j] + j)
Observe equation (1) and (4) are identical, similarly equation (2) and (3) are identical.
Now the task is to find the maximum value of these equation. So the approach is to form two arrays, first_array[], it will store arr[i] + i, 0 <= i < n, second_array[], it will store arr[i] – i, 0 <= i < n.
Now our task is easy we just need to find the maximum difference between two values these two arrays.
Now our task is easy we just need to find the maximum difference between two values these two arrays.
For that, we find maximum value and minimum value in first_array and store their difference:
ans1 = (maximum value in first_array – minimum value in first_array)
Similarly, we need to find maximum value and minimum value in second_array and store their difference:
ans2 = (maximum value in second_array – minimum value in second_array)
Our answer will be maximum of ans1 and ans2.
ans1 = (maximum value in first_array – minimum value in first_array)
Similarly, we need to find maximum value and minimum value in second_array and store their difference:
ans2 = (maximum value in second_array – minimum value in second_array)
Our answer will be maximum of ans1 and ans2.