Maximum value of |arr[i] – arr[j] - + |i – j| in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of n integers. Our task is to create a program that will find the maximum value of |arr[i]-arr[j]| + |i-j|.

Let’s take an example to understand the problem,

Input − array = {4, 1, 2}

Output − 4

Explanation

|arr[0] - arr[1]|+|0-1| = |4-1| + |-1| = 3+1 = 4
|arr[0] - arr[2]|+|0-2| = |4-2| + |-2| = 2+2 = 4
|arr[1] - arr[2 ]|+|1-2| = |1-2| + |1-2| = 1+1 = 2

To solve this problem, a simple approach will be using the brute force approach which will be using two loops and finding the max difference.

But an efficient approach will be using the properties of the absolute function,

Let’s decode the equation and find the solution,

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)}

First and forth are the same and the second and fourth are the same. Using this we will create two arrays that will store values arr[i]+- i.

array1 will store values arr[i] + i

array2 will store values arr[i] - i

So, we will find the maximum of two values that are

max ((max(array1)-min(array1)), (max(array2)-min(array2)))

Example

Program to show the implementation of our solution,

 Live Demo

#include<iostream>
using namespace std;
int maxDiff(int arr[], int n) {
   int ans = 0;
   for (int i = 0; i < n; i++)
      for (int j = 0; j < n; j++)
         ans = max(ans, abs(arr[i] - arr[j]) + abs(i - j));
   return ans;
}
int main() {
   int array[] = { 5, 7, 1, 2 };
   int n = sizeof(array) / sizeof(array[0]);
   cout<<"The maximum value of |arr[i] - arr[j]| + |i-j| is "<<maxDiff(array, n);
   return 0;
}

Output

The maximum value of |arr[i] - arr[j]| + |i-j| is 7
raja
Published on 10-Feb-2020 14:07:05
Advertisements