Maximum sum of absolute differences between distinct pairs of a triplet from an array
Last Updated :
01 Dec, 2022
Given an array arr[] consisting of N integers, the task is to find the maximum sum of absolute differences between all distinct pairs of the triplet in the array.
Examples:
Input: arr[] = {1, 2, 3, 4}
Output: 6
Explanation:
The valid triplet is (1, 3, 4) as sum = |1 – 4| + |1 – 3| + |3 – 4| = 6, which is the maximum among all the triplets.
Input: arr[] = {2, 2, 2}
Output: 0
Approach: The idea to solve the given problem is to sort the array in ascending order and find the sum of absolute differences between the pairs of the first and the last two elements of the array. Follow the steps below to solve the problem:
- Initialize a variable, say sum, to store the maximum possible sum.
- Sort the given array arr[] in ascending order.
- Find the sum of differences between the pairs of the first and the last two elements of the array i.e., sum = (arr[N – 2] – arr[0]) + (arr[N – 1] – arr[0]) + (arr[N – 2] – arr[N – 1]).
- After completing the above steps, print the value of the sum as the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void maximumSum( int arr[], int N)
{
int sum;
sort(arr, arr + N);
sum = (arr[N - 1] - arr[0])
+ (arr[N - 2] - arr[0])
+ (arr[N - 1] - arr[N - 2]);
cout << sum;
}
int main()
{
int arr[] = { 1, 3, 4, 2 };
int N = sizeof (arr) / sizeof (arr[0]);
maximumSum(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void maximumSum( int [] arr, int N)
{
int sum;
Arrays.sort(arr);
sum = (arr[N - 1 ] - arr[ 0 ]) + (arr[N - 2 ] - arr[ 0 ])
+ (arr[N - 1 ] - arr[N - 2 ]);
System.out.println(sum);
}
public static void main(String[] args)
{
int [] arr = { 1 , 3 , 4 , 2 };
int N = arr.length;
maximumSum(arr, N);
}
}
|
Python3
def maximumSum(arr, N):
sum = 0
arr.sort()
sum = (arr[N - 1 ] - arr[ 0 ]) + (arr[N - 2 ] - arr[ 0 ]) + (arr[N - 1 ] - arr[N - 2 ]);
print ( sum )
arr = [ 1 , 3 , 4 , 2 ]
N = len (arr)
maximumSum(arr, N)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void maximumSum( int [] arr, int N)
{
int sum;
Array.Sort(arr);
sum = (arr[N - 1] - arr[0]) + (arr[N - 2] - arr[0])
+ (arr[N - 1] - arr[N - 2]);
Console.Write(sum);
}
public static void Main()
{
int [] arr = { 1, 3, 4, 2 };
int N = arr.Length;
maximumSum(arr, N);
}
}
|
Javascript
<script>
function maximumSum(arr, N)
{
let sum;
arr.sort();
sum = (arr[N - 1] - arr[0])
+ (arr[N - 2] - arr[0])
+ (arr[N - 1] - arr[N - 2]);
document.write(sum);
}
let arr = [ 1, 3, 4, 2 ];
let N = arr.length;
maximumSum(arr, N);
</script>
|
Time Complexity: O(N*log N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...