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

C++Server Side ProgrammingProgramming

## Problem statement

Given an 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

If input array is: {1, 2, 3, 1} then output is 4 if we choose i = 0 and j = 4

## Algorithm

1. The idea is to use brute force i.e. iterate in two for loops

## Example

#include <bits/stdc++.h>
using namespace std;
#define MAX 10
int getResult(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 arr[] = {1, 2, 3, 1};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Result = " << getResult(arr, n) << endl;
return 0;
}

## Output

When you compile and execute the above program. It generates the following output −

Result = 4
Published on 10-Feb-2020 09:37:05