Open In App

Find maximum absolute difference with min sum of ratios in an Array

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of positive integers arr[], the task is to find the maximum absolute difference between the pairs from the array such that the sum of their ratios is minimum.

Examples:

Input: arr[] = {2, 6, 3, 4, 8, 9}
Output: 4
Explanation: In the above example, the ratios of every pair are calculated likewise between 2 and 6 (1:3), 2 and 3 (2:3), 6 and 3 (2:1), 3 and 4 (3:4), 4 and 8 (1:2) and so on. Here the minimum ratio sum is 3 i.e., (1:2 or 2:1) where the pairs like [6, 3], [2, 4] and [4, 8] have the above ratio, and even in them the maximum absolute difference is 4 i.e.,  
abs(4-8) = 4

Input: arr[] = {5, 9, 10, 18, 12};
Output: 9
Explanation: The pair [9, 18] is having minimum ratio sum of 3(1:2) and a maximum absolute difference of 9.

Approach: This can be solved with the following idea:

The approach is to choose two numbers from the array and calculate their ratio in the form of a:b (integer ratio numerator and denominator) by dividing them with their GCD. Add these two integers and check if it is less than the minimum ratio sum found so far. If yes, it updates the minimum ratio sum and calculates the absolute difference between the two numbers, and stores it as the maximum difference found so far.

Below are the steps involved in the implementation of the code:

  • Initialize maxDiff to 0 and minRatioSum to Integer.MAX_VALUE.
  • For each pair (a, b) in arr such that a < b:
  • Compute the ratio of a and b as d1:d2 using the getRatio() function
    • If ratioSum < minRatioSum, update minRatioSum to ratioSum and maxDiff to abs(a – b)
    • Else if ratioSum is equal to minRatioSum, update maxDiff to max(maxDiff, abs(a – b))
  • Return maxDiff.

Below is the implementation of the above approach:

C++




// C++ code for the above approach:
#include <cmath>
#include <iostream>
#include <limits.h>
 
using namespace std;
 
// Function to getGCD
int getGCD(int i1, int i2)
{
    if (i1 == i2) {
        return i1;
    }
    if (i1 > i2) {
        return getGCD(i1 - i2, i2);
    }
    return getGCD(i1, i2 - i1);
}
 
// Function to find ratio
int* getRatio(int a, int b)
{
    int gcd = getGCD(a, b);
    int d1 = a / gcd;
    int d2 = b / gcd;
    int* ans = new int[2];
    ans[0] = d1;
    ans[1] = d2;
    return ans;
}
 
// Function to find maximum absolute
// difference
int maxAbsDiff(int arr[], int n)
{
    int maxDiff = 0;
    int minRatioSum = INT_MAX;
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            int a = arr[i];
            int b = arr[j];
            int ratioSum = 0;
            int* temp = getRatio(a, b);
 
            ratioSum = temp[0] + temp[1];
 
            if (ratioSum < minRatioSum) {
                minRatioSum = ratioSum;
                maxDiff = abs(a - b);
            }
            else if (ratioSum == minRatioSum) {
 
                // Update the maximum
                // abosulte differnce
                maxDiff = max(maxDiff, abs(a - b));
            }
        }
    }
    return maxDiff;
}
 
// Driver code
int main()
{
    int arr[] = { 2, 6, 3, 4, 8, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    int res = maxAbsDiff(arr, n);
    cout << res << endl;
    return 0;
}


Java




/*package whatever // do not write package name here */
 
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        int[] arr = { 2, 6, 3, 4, 8, 9 };
        int res = maxAbsDiff(arr);
        System.out.println("Maximum absolute difference : " + res);
    }
    public static int maxAbsDiff(int[] arr)
    {
        int n = arr.length;
        int maxDiff = 0;
        int minRatioSum = Integer.MAX_VALUE;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int a = arr[i];
                int b = arr[j];
                int ratioSum = 0;
                int[] temp = getRatio(a, b);
 
                ratioSum = temp[0] + temp[1];
 
                if (ratioSum < minRatioSum) {
                    minRatioSum = ratioSum;
                    maxDiff = Math.abs(a - b);
                }
                else if (ratioSum == minRatioSum) {
                    maxDiff = Math.max(maxDiff,
                                       Math.abs(a - b));
                }
            }
        }
        return maxDiff;
    }
    public static int[] getRatio(int a, int b)
    {
        int gcd = getGCD(a, b);
        int d1 = a / gcd;
        int d2 = b / gcd;
        int[] ans = { d1, d2 };
        return ans;
    }
 
    public static int getGCD(int i1, int i2)
    {
        if (i1 == i2)
            return i1;
        if (i1 > i2)
            return getGCD(i1 - i2, i2);
        return getGCD(i1, i2 - i1);
    }
}


Python3




# Python code for the above approach
import math
 
# Function to get GCD
def get_gcd(i1, i2):
    if i1 == i2:
        return i1
    if i1 > i2:
        return get_gcd(i1 - i2, i2)
    return get_gcd(i1, i2 - i1)
 
# Function to find ratio
def get_ratio(a, b):
    gcd = get_gcd(a, b)
    d1 = a // gcd
    d2 = b // gcd
    return [d1, d2]
 
# Function to find maximum absolute difference
def max_abs_diff(arr, n):
    max_diff = 0
    min_ratio_sum = math.inf
    for i in range(n):
        for j in range(i + 1, n):
            a = arr[i]
            b = arr[j]
            ratio_sum = 0
            temp = get_ratio(a, b)
            ratio_sum = temp[0] + temp[1]
 
            if ratio_sum < min_ratio_sum:
                min_ratio_sum = ratio_sum
                max_diff = abs(a - b)
            elif ratio_sum == min_ratio_sum:
                # Update the maximum absolute difference
                max_diff = max(max_diff, abs(a - b))
     
    return max_diff
 
# Driver code
if __name__ == "__main__":
    arr = [2, 6, 3, 4, 8, 9]
    n = len(arr)
 
    # Function call
    res = max_abs_diff(arr, n)
    print(res)


C#




// C# code for the above approach:
using System;
 
class GFG {
     
    public static void Main()
    {
        int[] arr = { 2, 6, 3, 4, 8, 9 };
       
        // Function call
        int res = maxAbsDiff(arr);
        Console.WriteLine("Maximum absolute difference : " + res);
    }
   
    // Function to find maximum absolute
    // difference
    public static int maxAbsDiff(int[] arr)
    {
        int n = arr.Length;
        int maxDiff = 0;
        int minRatioSum = int.MaxValue;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int a = arr[i];
                int b = arr[j];
                int ratioSum = 0;
                int[] temp = getRatio(a, b);
 
                ratioSum = temp[0] + temp[1];
 
                if (ratioSum < minRatioSum) {
                    minRatioSum = ratioSum;
                    maxDiff = Math.Abs(a - b);
                }
                else if (ratioSum == minRatioSum) {
                    maxDiff = Math.Max(maxDiff,
                                    Math.Abs(a - b));
                }
            }
        }
        // Update the maximum
        // abosulte differnce
        return maxDiff;
    }
   
     
    // Function to find ratio
    public static int[] getRatio(int a, int b)
    {
        int gcd = getGCD(a, b);
        int d1 = a / gcd;
        int d2 = b / gcd;
        int[] ans = { d1, d2 };
        return ans;
    }
 
      // Function to getGCD
    public static int getGCD(int i1, int i2)
    {
        if (i1 == i2)
            return i1;
        if (i1 > i2)
            return getGCD(i1 - i2, i2);
        return getGCD(i1, i2 - i1);
    }
}
 
// This code is contributed by Pushpesh Raj


Javascript




// Javascript code for the above approach
 
// Function to get GCD
function get_gcd(i1, i2) {
    if (i1 == i2) {
        return i1;
    }
    if (i1 > i2) {
        return get_gcd(i1 - i2, i2);
    }
    return get_gcd(i1, i2 - i1);
}
 
// Function to find ratio
function get_ratio(a, b) {
    gcd = get_gcd(a, b);
    d1 = a / gcd;
    d2 = b / gcd;
    return [d1, d2];
}
 
// Function to find maximum absolute difference
function max_abs_diff(arr, n) {
    max_diff = 0;
    min_ratio_sum = Number.MAX_VALUE;
    for (i = 0; i < n; i++) {
        for (j = i + 1; j < n; j++) {
            a = arr[i];
            b = arr[j];
            ratio_sum = 0;
            temp = get_ratio(a, b);
            ratio_sum = temp[0] + temp[1];
 
            if (ratio_sum < min_ratio_sum) {
                min_ratio_sum = ratio_sum;
                max_diff = Math.abs(a - b);
            } else if (ratio_sum == min_ratio_sum) {
                // Update the maximum absolute difference
                max_diff = Math.max(max_diff, Math.abs(a - b));
            }
        }
    }
    return max_diff;
}
 
// Driver code
arr = [2, 6, 3, 4, 8, 9];
n = arr.length;
 
// function call
res = max_abs_diff(arr, n);
console.log(res);
 
// This code is contributed by Tapesh(tapeshdua420)


Output

4






Time Complexity: O(N2)
Auxiliary Space: O(1)



Last Updated : 24 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads