Maximum value of division of two numbers in an Array
Last Updated :
31 May, 2022
Given an array A of size N (> 2). The task is to find the maximum value of A[i] / A[j]
Note: A[i] ? 0.
Examples:
Input : A[] = {1, 2, 3, 4}
Output : 4
4 / 1 = 4 is maximum possible value.
Input : A[] = {3, 7, 9, 3, 11}
Output : 3
Naive Approach: A naive approach is to run nested loops and find the maximum possible answer.
Time complexity : O(N2).
Efficient Approach: An efficient approach is to find maximum and minimum element in the array and print maximum / minimum
Proof:
Lets take an array A[] = {a, b, c, d} where a < b < c < d .
Now :
(b / a) < ( c / a ) < (d / a) (since b < c < d, and denominator is constant )
and since a is minimum, therefore
d / a is maximum
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int Division( int a[], int n)
{
int maxi = INT_MIN, mini = INT_MAX;
for ( int i = 0; i < n; i++)
{
maxi = max(a[i], maxi);
mini = min(a[i], mini);
}
return maxi / mini;
}
int main()
{
int a[] = {3, 7, 9, 3, 11};
int n = sizeof (a) / sizeof (a[0]);
cout << Division(a, n);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
static int Division( int a[], int n)
{
int maxi = Integer.MIN_VALUE,
mini = Integer.MAX_VALUE;
for ( int i = 0 ; i < n; i++)
{
maxi = Math.max(a[i], maxi);
mini = Math.min(a[i], mini);
}
return maxi / mini;
}
public static void main (String[] args)
throws java.lang.Exception
{
int a[] = { 3 , 7 , 9 , 3 , 11 };
int n = a.length;
System.out.print(Division(a, n));
}
}
|
Python3
def Division(a, n):
maxi = - 10 * * 9
mini = 10 * * 9
for i in a:
maxi = max (i, maxi)
mini = min (i, mini)
return maxi / / mini
a = [ 3 , 7 , 9 , 3 , 11 ]
n = len (a)
print (Division(a, n))
|
C#
using System;
class GFG
{
static int Division( int []a, int n)
{
int maxi = int .MinValue,
mini = int .MaxValue;
for ( int i = 0; i < n; i++)
{
maxi = Math.Max(a[i], maxi);
mini = Math.Min(a[i], mini);
}
return maxi / mini;
}
public static void Main (String[] args)
{
int []a = {3, 7, 9, 3, 11};
int n = a.Length;
Console.WriteLine(Division(a, n));
}
}
|
Javascript
<script>
function Division(a, n)
{
let maxi = Number.MIN_VALUE, mini = Number.MAX_VALUE;
for (let i = 0; i < n; i++)
{
maxi = Math.max(a[i], maxi);
mini = Math.min(a[i], mini);
}
return parseInt(maxi / mini);
}
let a = [3, 7, 9, 3, 11];
let n = a.length;
document.write(Division(a, n));
</script>
|
Output :
3
Time complexity : O(N), since the loop runs only once from 0 to (n – 1).
Auxiliary space : O(1), since no extra space has been taken.
Note: Above solution works only for positive integers
Share your thoughts in the comments
Please Login to comment...