Maximum value of |arr[0] – arr[1]| + |arr[1] – arr[2]| + … +|arr[n – 2] – arr[n – 1]| when elements are from 1 to n
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 order.
Examples:
Input: arr[] = {1, 2, 3, 4}
Output: 7
Arrange the array in this way for max value, arr[] = {3, 1, 4, 2}
|3 – 1| + |1 – 4| + |4 – 2| = 2 + 3 + 2 = 7
Input: arr[] = {1, 2, 3}
Output: 3
We arrange the array as {2, 1, 3}
A Simple Approach is to generate all possible permutations. Compute the value for every permutation and find the maximum value.
Efficient Approach:
The maximum sum with one element is 0.
The maximum sum with two elements is 1
The maximum sum with three elements is 3 (explained above)
The maximum sum with four elements is 7 (explained above)
It can be observed that for different values of n, a pattern for the maximum sum of absolute differences is 0, 1, 3, 7, 11, 17, 23, 31, 39, 49, ….. whose nth term is ((n * n / 2) – 1).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxValue( int n)
{
if (n == 1)
return 0;
return ((n * n / 2) - 1);
}
int main()
{
int n = 4;
cout << maxValue(n);
return 0;
}
|
Java
class GFG {
static int maxValue( int n)
{
if (n == 1 )
return 0 ;
return ((n * n / 2 ) - 1 );
}
public static void main(String args[])
{
int n = 4 ;
System.out.print(maxValue(n));
}
}
|
Python
def maxValue(n):
if (n = = 1 ):
return 0
return (( n * n / / 2 ) - 1 )
n = 4
print (maxValue(n))
|
C#
using System;
class GFG {
static int maxValue( int n)
{
if (n == 1)
return 0;
return ((n * n / 2) - 1);
}
public static void Main()
{
int n = 4;
Console.WriteLine(maxValue(n));
}
}
|
PHP
<?php
function maxValue( $n )
{
if ( $n == 1)
return 0;
return (( $n * $n / 2) - 1);
}
$n = 4;
echo maxValue( $n );
?>
|
Javascript
<script>
function maxValue(n)
{
if (n == 1)
return 0;
return (parseInt(n * n / 2) - 1);
}
var n = 4;
document.write(maxValue(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
24 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...