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

Problem statement

Given an array arr[] of size n whose elements are from the range [1, n]. The task is to find maximum value of |arr[0] – arr[1]| + |arr[1] – arr[2]| + … +|arr[n – 2] – arr[n – 1]|.

You can arrange the numbers in the array in any orders.

If the input array is {1, 3, 2, 4} then we can re-arrange array as follows to obtain maximum result −

{3, 1, 4, 2}
|3 – 1| + |1 – 4| + |4 – 2| = 2 + 3 + 2 = 7

Algorithm

We can obtain result using below formula −

((n * n / 2) - 1)

Example

#include <bits/stdc++.h>
using namespace std;
int getMaxValue(int n){
   if (n == 1) {
      return 0;
   }
   return ((n * n / 2) - 1);
}
int main(){
   int n = 5;
   cout << "Result = " << getMaxValue(n) << endl;
   return 0;
}

Output

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

Result = 11
raja
Published on 10-Feb-2020 09:35:09
Advertisements