Maximum sum of difference of adjacent elements
Last Updated :
25 Aug, 2021
Given a number n. We have to find maximum sum of all permutations of n. The maximum sum will be sum of absolute difference of adjacent elements in array.
Examples:
Input : 3
Output : 3
Permutations of size 3 are:
{1, 2, 3} = 1 + 1
{1, 3, 2} = 2 + 1
{2, 1, 3} = 1 + 2
{2, 3, 1} = 1 + 2
{3, 1, 2} = 2 + 1
{3, 2, 1} = 1 + 1
Input : 2
Output : 1
Permutations of 2 are:
{1, 2} = 1
{2, 1} = 1
Let us take example of n = 5. We can easily see we can place numbers like 1 5 2 4 3.
abs(1-5) = 4
abs(5-2) = 3
abs(2-4) = 2
abs(4-3) = 1
which sum is 4 + 3 + 2 + 1 = 10.
In general sum of this permutation is n(n-1)/2.
But the maximum sum is obtained if we move 3 at beginning of this permutation
ie 3 1 5 2 4.
Sum will become 2 + 4 + 3 + 2 = 11.
Final relation = n (n – 1) / 2 – 1 + n / 2 for n > 1.
The permutation of n having maximum sum will be of from n/2, n-1, 2, n-2, 3, n-3.
So we have to find sum of this permutation which will be n(n-1)/2 – 1 + n/2.
Below is implementation of above approach.
C++
#include <iostream>
using namespace std;
int maxSum( int n)
{
if (n == 1)
return 1;
else
return (n * (n - 1) / 2) - 1 + n / 2;
}
int main()
{
int n = 3;
cout << maxSum(n);
return 0;
}
|
Java
public class Main {
static int maxSum( int n)
{
if (n == 1 )
return 1 ;
else
return (n * (n - 1 ) / 2 ) - 1 + n / 2 ;
}
public static void main(String[] args)
{
int n = 3 ;
System.out.println(maxSum(n));
}
}
|
Python3
def maxSum(n):
if (n = = 1 ):
return 1
else :
return int ((n * (n - 1 ) / 2 ) - 1 + n / 2 )
n = 3
print (maxSum(n))
|
C#
using System;
public class main {
static int maxSum( int n)
{
if (n == 1)
return 1;
else
return (n * (n - 1) / 2)
- 1 + n / 2;
}
public static void Main()
{
int n = 3;
Console.WriteLine(maxSum(n));
}
}
|
PHP
<?php
function maxSum( $n )
{
if ( $n == 1)
return 1;
else
return ( $n * ( $n - 1) / 2) -
1 + $n / 2;
}
$n = 3;
echo intval ( maxSum( $n ));
?>
|
Javascript
<script>
function maxSum(n)
{
if (n == 1)
return 1;
else
return (parseInt(n * (n - 1) / 2, 10) - 1 +
parseInt(n / 2, 10));
}
let n = 3;
document.write(maxSum(n));
</script>
|
Output:
3
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...