Maximize sum of absolute difference between adjacent elements in Array with sum K
Given two integers N and K, the task is to maximize the sum of absolute differences between adjacent elements of an array of length N and sum K.
Examples:
Input: N = 5, K = 10
Output: 20
Explanation:
The array arr[] with sum 10 can be {0, 5, 0, 5, 0}, maximizing the sum of absolute difference of adjacent elements ( 5 + 5 + 5 + 5 = 20)
Input: N = 2, K = 10
Output: 10
Approach:
To maximize the sum of adjacent elements, follow the steps below:
- If N is 2, the maximum sum possible is K by placing K in 1 index and 0 on the other.
- If N is 1, the maximum sum possible will always be 0.
- For all other values of N, the answer will be 2 * K.
Illustration:
For N = 3, the arrangement {0, K, 0} maximizes the sum of absolute difference between adjacent elements to 2 * K.
For N = 4, the arrangement {0, K/2, 0, K/2} or {0, K, 0, 0} maximizes the required sum of absolute difference between adjacent elements to 2 * K.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxAdjacentDifference( int N, int K)
{
if (N == 1) {
return 0;
}
if (N == 2) {
return K;
}
return 2 * K;
}
int main()
{
int N = 6;
int K = 11;
cout << maxAdjacentDifference(N, K);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int maxAdjacentDifference( int N, int K)
{
if (N == 1 )
{
return 0 ;
}
if (N == 2 )
{
return K;
}
return 2 * K;
}
public static void main(String[] args)
{
int N = 6 ;
int K = 11 ;
System.out.print(maxAdjacentDifference(N, K));
}
}
|
Python3
def maxAdjacentDifference(N, K):
if (N = = 1 ):
return 0 ;
if (N = = 2 ):
return K;
return 2 * K;
N = 6 ;
K = 11 ;
print (maxAdjacentDifference(N, K));
|
C#
using System;
class GFG{
static int maxAdjacentDifference( int N, int K)
{
if (N == 1)
{
return 0;
}
if (N == 2)
{
return K;
}
return 2 * K;
}
public static void Main(String[] args)
{
int N = 6;
int K = 11;
Console.Write(maxAdjacentDifference(N, K));
}
}
|
Javascript
<script>
function maxAdjacentDifference(N, K)
{
if (N == 1)
{
return 0;
}
if (N == 2)
{
return K;
}
return 2 * K;
}
let N = 6;
let K = 11;
document.write(maxAdjacentDifference(N, K));
</script>
|
Time Complexity: O(1).
Auxiliary Space: O(1)
Last Updated :
30 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...