Maximize difference between the sum of absolute differences of each element with the remaining array
Given an array arr[] consisting of N integers, the task is to maximize the difference between the sum of absolute difference of an element with the remaining elements in the array.
Examples:
Input: arr[] = {1, 2, 4, 7}
Output: 6
Explanation:
For i = 1, |1 – 2| + |1 – 4| + |1 – 7| = 1 + 3 + 6 =10.
For i = 2, |2 – 1| + |2 – 4| + |2 – 7| = 1 + 2 + 5 = 8.
For i = 3, |4 – 1| + |4 – 2| + |4 – 7| = 3 + 2 + 3 = 8.
For i = 4, |7 – 1| + |7 – 2| + |7 – 4| = 6 + 5 + 3 = 14.
Maximum=14, Minimum=8.
Therefore, the maximum difference = 14 – 8 = 6.
Input: arr[] = {2, 1, 5, 4, 3}
Output: 4
Naive Approach: The simplest idea is to traverse the array and for each array element, traverse the array using a nested loop and calculate and store the sum of its absolute difference with the remaining array. While calculating, keep track of the maximum and minimum sums obtained. Finally, print the difference between the maximum and minimum sums.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findMaxDifference( int arr[], int n)
{
int Max = INT_MIN;
int Min = INT_MAX;
for ( int i = 0; i < n; i++) {
int sum = 0;
for ( int j = 0; j < n; j++) {
sum += abs (arr[i] - arr[j]);
}
Max = max(Max, sum);
Min = min(Min, sum);
}
cout << Max - Min << endl;
}
int main()
{
int arr[] = {1, 2, 4, 7};
int n = sizeof (arr) / sizeof (arr[0]);
findMaxDifference(arr, n);
return 0;
}
|
Java
import java.util.*;
public class GFG {
static void findMaxDifference( int [] arr, int n)
{
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for ( int i = 0 ; i < n; i++) {
int sum = 0 ;
for ( int j = 0 ; j < n; j++) {
sum += Math.abs(arr[i] - arr[j]);
}
max = Math.max(max, sum);
min = Math.min(min, sum);
}
System.out.println(max - min);
}
public static void main(String[] args)
{
int [] arr = { 1 , 2 , 4 , 7 };
int n = arr.length;
findMaxDifference(arr, n);
}
}
|
Python
def find_max_difference(arr):
max_val = float ( '-inf' )
min_val = float ( 'inf' )
for i in range ( len (arr)):
total_sum = 0
for j in range ( len (arr)):
total_sum + = abs (arr[i] - arr[j])
max_val = max (max_val, total_sum)
min_val = min (min_val, total_sum)
print (max_val - min_val)
if __name__ = = "__main__" :
arr = [ 1 , 2 , 4 , 7 ]
find_max_difference(arr)
|
C#
using System;
class GFG {
static void FindMaxDifference( int [] arr, int n)
{
int max = int .MinValue;
int min = int .MaxValue;
for ( int i = 0; i < n; i++) {
int sum = 0;
for ( int j = 0; j < n; j++) {
sum += Math.Abs(arr[i] - arr[j]);
}
max = Math.Max(max, sum);
min = Math.Min(min, sum);
}
Console.WriteLine(max - min);
}
static void Main()
{
int [] arr = { 1, 2, 4, 7 };
int n = arr.Length;
FindMaxDifference(arr, n);
}
}
|
Javascript
function findMaxDifference(arr, n)
{
let Max = Number.MIN_SAFE_INTEGER;
let Min = Number.MAX_SAFE_INTEGER;
for (let i = 0; i < n; i++) {
let sum = 0;
for (let j = 0; j < n; j++) {
sum += Math.abs(arr[i] - arr[j]);
}
Max = Math.max(Max, sum);
Min = Math.min(Min, sum);
}
console.log(Max - Min);
}
let arr = [1, 2, 4, 7];
let n = arr.length;
findMaxDifference(arr, n);
|
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is based on the observation that in a sorted array, for any index i, the elements on its left will be smaller and elements on its right will be greater. The sum of absolute difference for any element arr[i] in this sorted array can be calculated using the following formula:
(Number of elements to its left)*(arr[i]) – Sum of elements to its left + Sum of elements to its right – (Number of elements to its right)*(arr[i]))
Follow the steps below to solve the problem:
- Initialize totalSum as 0 to store the sum of all the element of the array and leftSum as 0 to store the sum of elements on the left of any index.
- Initialize two variables, Max as INT_MIN and Min as INT_MAX.
- Sort the array arr[] in ascending order.
- Traverse the array, arr[] using the variable i and do the following:
- Store the sum of absolute difference of arr[i] with the rest of the elements using the formula in Sum = (i * arr[i]) – leftSum + totalSum – ((N – i – 1) * arr[i]).
- Update Max to the maximum of Max and Sum.
- Update Min to the minimum of Min and Sum.
- After the above steps, print the value of Max and Min as the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findMaxDifference( int arr[], int n)
{
sort(arr, arr + n);
int Leftsum = 0;
int Totalsum = 0;
int Min = INT_MAX, Max = INT_MIN;
for ( int i = 0; i < n; i++)
Totalsum += arr[i];
for ( int i = 0; i < n; i++) {
int leftNumbers = i;
int rightNumbers = n - i - 1;
Totalsum = Totalsum - arr[i];
int sum = (leftNumbers * arr[i])
- Leftsum
+ Totalsum
- (rightNumbers * arr[i]);
Min = min(Min, sum);
Max = max(Max, sum);
Leftsum += arr[i];
}
cout << Max - Min;
}
int main()
{
int arr[] = { 1, 2, 4, 7 };
int N = sizeof (arr) / sizeof (arr[0]);
findMaxDifference(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void findMaxDifference( int arr[], int n)
{
Arrays.sort(arr);
int Leftsum = 0 ;
int Totalsum = 0 ;
int Min = Integer.MAX_VALUE, Max = Integer.MIN_VALUE;
for ( int i = 0 ; i < n; i++)
Totalsum += arr[i];
for ( int i = 0 ; i < n; i++)
{
int leftNumbers = i;
int rightNumbers = n - i - 1 ;
Totalsum = Totalsum - arr[i];
int sum = (leftNumbers * arr[i])
- Leftsum
+ Totalsum
- (rightNumbers * arr[i]);
Min = Math.min(Min, sum);
Max = Math.max(Max, sum);
Leftsum += arr[i];
}
System.out.print(Max - Min);
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 4 , 7 };
int N = arr.length;
findMaxDifference(arr, N);
}
}
|
Python3
def findMaxDifference(arr, n):
arr = sorted (arr)
Leftsum = 0
Totalsum = 0
Min , Max = 10 * * 8 , - 10 * * 8
for i in range (n):
Totalsum + = arr[i]
for i in range (n):
leftNumbers = i
rightNumbers = n - i - 1
Totalsum = Totalsum - arr[i]
sum = (leftNumbers * arr[i]) - Leftsum + Totalsum - (rightNumbers * arr[i])
Min = min ( Min , sum )
Max = max ( Max , sum )
Leftsum + = arr[i]
print ( Max - Min )
if __name__ = = '__main__' :
arr = [ 1 , 2 , 4 , 7 ]
N = len (arr)
findMaxDifference(arr, N)
|
C#
using System;
class GFG
{
static void findMaxDifference( int [] arr, int n)
{
Array.Sort(arr);
int Leftsum = 0;
int Totalsum = 0;
int Minn = Int32.MaxValue, Maxx = Int32.MinValue;
for ( int i = 0; i < n; i++)
Totalsum += arr[i];
for ( int i = 0; i < n; i++)
{
int leftNumbers = i;
int rightNumbers = n - i - 1;
Totalsum = Totalsum - arr[i];
int sum = (leftNumbers * arr[i])
- Leftsum
+ Totalsum
- (rightNumbers * arr[i]);
Minn = Math.Min(Minn, sum);
Maxx = Math.Max(Maxx, sum);
Leftsum += arr[i];
}
Console.WriteLine(Maxx - Minn);
}
public static void Main(String[] args)
{
int [] arr = { 1, 2, 4, 7 };
int N = arr.Length;
findMaxDifference(arr, N);
}
}
|
Javascript
<script>
function findMaxDifference(arr, n)
{
arr.sort();
let Leftsum = 0;
let Totalsum = 0;
let Min = Number.MAX_VALUE, Max = Number.MIN_VALUE;
for (let i = 0; i < n; i++)
Totalsum += arr[i];
for (let i = 0; i < n; i++)
{
let leftNumbers = i;
let rightNumbers = n - i - 1;
Totalsum = Totalsum - arr[i];
let sum = (leftNumbers * arr[i])
- Leftsum
+ Totalsum
- (rightNumbers * arr[i]);
Min = Math.min(Min, sum);
Max = Math.max(Max, sum);
Leftsum += arr[i];
}
document.write(Max - Min);
}
let arr = [ 1, 2, 4, 7 ];
let N = arr.length;
findMaxDifference(arr, N);
</script>
|
Time Complexity: O(N*log N)
Auxiliary Space: O(1)
Last Updated :
21 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...