# Find Maximum value of abs(i – j) * min(arr[i], arr[j]) in an array arr[] in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] insisting of N integer values.Our task is to Find Maximum value of abs(i – j) * min(arr[i], arr[j]) in an array arr[].

Problem description − we need to find the maximum product value of the minimum value of two elements and the absolute differences between their indexes. i.e. for two values i and j, we need to maximise, abs(i - j) * min(arr[i] , arr[j]).

## Input

arr[] = {5, 7, 3, 6, 4}

## Output

16

## Explanation

The maximum value is 16, between index 0 and 4
=> abs(0 - 4)*min(arr[0], arr[4])
=> 4*min(5, 4) => 4*4 = 16

## Solution approach

A simple solution to the problem is using nested loops. we will take two loops and compute the value for each pair of i and j. And then return the maximum of all values found.

This approach is good but has a time complex of the order O(n2).

An effective solution to the problem is using two iterator values, from the start of the other from the end of the array. For each value of the iterators we will find the required value and compare them and store the maximum in maxVal variable. We will do this till both the iterators cross each other and at the end return the maxVal.

Program to illustrate the working of our solution,

## Example

Live Demo

#include<iostream>
using namespace std;
int calcMaxProdValue(int arr[], int n) {
int maxVal = -100;
int currentVal;
int start = 0, end = n-1;
while (start < end) {
if (arr[start] < arr[end]) {
currentVal = arr[start]*(end-start);
start++;
}
else {
currentVal = arr[end]*(end-start);
end--;
}
maxVal = max(maxVal, currentVal);
}
return maxVal;
}
int main(){
int arr[] = {5, 7, 3, 6, 4};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<"The maximum value of abs(i – j) * min(arr[i], arr[j]) in an array is "<<calcMaxProdValue(arr,n);
return 0;
}

## Output

The maximum value of abs(i – j) * min(arr[i], arr[j]) in an array is 16
Updated on 12-Mar-2021 06:30:15