Maximum sum of difference of adjacent elements in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a number N. Our task is to create a program to find the Maximum sum of difference of adjacent elements in C++.

Problem Description

We will find the Maximum sum of the absolute difference between the adjacent elements of all permutation arrays.

Let’s take an example to understand the problem,

Input

N = 4

Output

7

Explanation

All permutations of size 4 are :
{1, 2, 3, 4} = 1 + 1 + 1 = 3
{1, 2, 4, 3} = 1 + 2 + 1 = 4
{1, 3, 2, 4} = 2 + 1 + 2 = 5
{1, 3, 4, 2} = 2 + 1 + 2 = 5
{1, 4, 2, 3} = 3 + 2 + 1 = 6
{1, 4, 3, 2} = 3 + 1 + 1 = 5
{2, 1, 3, 4} = 1 + 2 + 1 = 4
{2, 1, 4, 3} = 1 + 3 + 1 = 5
{2, 3, 1, 4} = 1 + 2 + 3 = 6
{2, 3, 4, 1} = 1 + 1 + 3 = 5
{2, 4, 1, 3} = 2 + 3 + 2 = 7
{2, 4, 3, 1} = 2 + 1 + 2 = 5
{3, 1, 2, 4} = 2 + 1 + 2 = 5
{3, 1, 4, 2} = 2 + 3 + 2 = 7
{3, 2, 1, 4} = 1 + 1 + 3 = 5
{3, 2, 4, 1} = 1 + 2 + 3 = 6
{3, 4, 1, 2} = 1 + 3 + 1 = 5
{3, 4, 2, 1} = 1 + 2 + 1 = 4
{4, 1, 2, 3} = 3 + 1 + 1 = 5
{4, 1, 3, 2} = 3 + 2 + 1 = 6
{4, 2, 1, 3} = 2 + 1 + 2 = 5
{4, 2, 3, 1} = 2 + 1 + 2 = 5
{4, 3, 1, 2} = 1 + 2 + 1 = 4
{4, 3, 2, 1} = 1 + 1 + 1 = 3

Solution Approach

To solve this type of problem, we need to find the general sum of the permutation.

Here, are some values of the Maximum sum of difference of adjacent elements for different values of N.

N = 2, maxSum = 1
N = 3, maxSum = 3
N = 4, maxSum = 7
N = 5, maxSum = 11
N = 6, maxSum = 17
N = 7, maxSum = 23
N = 8, maxSum = 31

This sum looks like an addition dependent of N + sum of N terms

maxSum = S(N) + F(N) S(N) = n(n-1)/2, and F(N) is an unknown function of N

Let’s find F(N) using S(N), maxSum(N).

F(2) = 0
F(3) = 0
F(4) = 1
F(5) = 1
F(6) = 2
F(7) = 2
F(8) = 3

From here, we can derive that F(N) is Int(N/2 - 1). F(N) increases for every second value of N and initially for 2 and 3 it is zero.

This makes the formula for maxSum,

maxSum = N(N-1)/2 + N/2 - 1
maxSum = N(N-1)/2 + N/2 - 2/2
maxSum = ( N(N-1) + N - 2 )/2
maxSum = ( (N^2) - N + N - 2 )/2
maxSum = ((N^2) - 2 )/2

Using this formula, we can find the maxSum value of any given value of N.

Example

Program to illustrate the working of our solution,

 Live Demo

#include <iostream>
using namespace std;
int calcMaxSumofDiff(int N){
   int maxSum = 0;
   maxSum = ((N*N) - 2) /2 ;
   return maxSum;
}
int main(){
   int N = 13;
   cout<<"The maximum sum of difference of adjacent elements is "<<calcMaxSumofDiff(N);
   return 0;
}

Output

The maximum sum of difference of adjacent elements is 83
raja
Published on 22-Jul-2020 08:26:33
Advertisements