Minimum sum of absolute differences between pairs of a triplet from an array
Last Updated :
09 Jul, 2021
Given an array A[] consisting of positive integers, the task is to find the minimum value of |A[x] – A[y]| + |A[y] – A[z]| of any triplet (A[x], A[y], A[z]) from an array.
Examples:
Input: A[] = { 1, 1, 2, 3 }
Output: 1
Explanation:
For x = 0, y = 1, z = 2
|A[x] – A[y]| + |A[y] – A[z]| = 0 + 1 = 1, which is maximum possible
Input : A[] = { 1, 1, 1 }
Output : 0
Approach : The problem can be solved greedily. Follow the steps below to solve the problem:
- Traverse the array.
- Sort the array in ascending order.
- Traverse the array using a variable i over indices [0, N – 3]. For every ith index, set x = i, y = i + 1, z = i + 2
- Calculate the sum of the triplet (x, y, z).
- Update the minimum sum possible.
- Print the minimum sum obtained.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minimum_sum( int A[], int N)
{
sort(A, A + N);
int sum = INT_MAX;
for ( int i = 0; i <= N - 3; i++) {
sum = min(sum,
abs (A[i] - A[i + 1]) +
abs (A[i + 1] - A[i + 2]));
}
cout << sum;
}
int main()
{
int A[] = { 1, 1, 2, 3 };
int N = sizeof (A) / sizeof (A[0]);
minimum_sum(A, N);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int minimum_sum( int []A, int N)
{
Arrays.sort(A);
int sum = 2147483647 ;
for ( int i = 0 ; i <= N - 3 ; i++) {
sum = Math.min(sum,Math.abs(A[i] - A[i + 1 ]) + Math.abs(A[i + 1 ] - A[i + 2 ]));
}
return sum;
}
public static void main(String[] args)
{
int []A = { 1 , 1 , 2 , 3 };
int N = A.length;
System.out.print(minimum_sum(A, N));
}
}
|
Python3
import sys
def minimum_sum(A, N):
A.sort(reverse = False )
sum = sys.maxsize
for i in range (N - 2 ):
sum = min ( sum , abs (A[i] - A[i + 1 ]) + abs (A[i + 1 ] - A[i + 2 ]))
print ( sum )
if __name__ = = '__main__' :
A = [ 1 , 1 , 2 , 3 ]
N = len (A)
minimum_sum(A, N)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int minimum_sum( int []A, int N)
{
Array.Sort(A);
int sum = 2147483647;
for ( int i = 0; i <= N - 3; i++) {
sum = Math.Min(sum,Math.Abs(A[i] - A[i + 1]) + Math.Abs(A[i + 1] - A[i + 2]));
}
return sum;
}
public static void Main()
{
int []A = { 1, 1, 2, 3 };
int N = A.Length;
Console.WriteLine(minimum_sum(A, N));
}
}
|
Javascript
<script>
function minimum_sum( A, N)
{
A.sort();
var sum = 1000000000;
for ( var i = 0; i <= N - 3; i++) {
sum = Math.min(sum,
Math.abs(A[i] - A[i + 1]) +
Math.abs(A[i + 1] - A[i + 2]));
}
document.write(sum);
}
var A = [ 1, 1, 2, 3 ];
var N = A.length;
minimum_sum(A, N);
</script>
|
Time Complexity : O(N * logN)
Auxiliary Space : O(1)
Share your thoughts in the comments
Please Login to comment...