Maximum value of |arr[0] – arr[1] - + |arr[1] – arr[2] - + … +|arr[n – 2] – arr[n – 1] - when elements are from 1 to n in C++

C++Server Side ProgrammingProgramming

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

Let’s take an example to understand the problem,

Input − array= {1, 2, 3}

Output − 3

Explanation

max sum is
|1-3|+|2-1| = 3

To solve this problem, a simple approach is to create all permutations from the array. And find the maximum value of all the values from permutation. A more effective method is to generalize all the maximum values for each value of n and then create a general formula.

So,

Maximum sum for (n = 1) = 0
Maximum sum for (n = 2) = 1
Maximum sum for (n = 3) = 3
Maximum sum for (n = 4) = 7
Maximum sum for (n = 5) = 11
So, the maximum value is 0, 1, 3, 7, 11…

The general formula is, ((n*n/2)-1)

Example

Program to illustrate the working of our solution,

 Live Demo

#include <iostream>
using namespace std;
int maxAbsVal(int n) {
   if (n == 1)
      return 0;
   return ((n*n/2) - 1);
}
int main() {
   int n = 4;
   cout<<"The maximum sum of absolute difference is "<<maxAbsVal(n);
   return 0;
}

Output

The maximum sum of absolute difference is 7
raja
Published on 10-Feb-2020 14:05:09
Advertisements