Maximize the division result of Array using given operations
Last Updated :
19 Oct, 2022
Given an array arr[] of N integers, the task is to find the maximum value possible remaining in the array by repeating the following two steps:
- Remove any two array elements.
- Insert the quotient of their division into the array.
Note: We are allowed to change the order of elements.
Examples:
Input: arr[] = {100, 1000, 10, 2}
Output: 200
Explanation:
- Remove 100 and 10 from the array. Insert 10 (= 100/10) back into the array.
- Remove 10 and 2 from the array. Insert 5 into the array.
- Remove 1000 and 5 from the array. Insert 200 into the array
Hence, the maximum result is 200.
Input: arr[] = {2, 100, 1}
Output: 50
Approach:
To solve the problem mentioned above, we can observe that we will get the maximum result when the elements are sorted in decreasing order and the division operations occur in the sequence arr[0] / ( arr[1] / arr[2] / arr[3]…..arr[n-1]) of the reversely sorted array. Hence, sort the array accordingly and calculate the appropriate result.
Below code is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
float maxDivision( int arr[], int n)
{
sort(arr, arr + n, greater< int >());
float mxdiv = arr[1];
for ( int i = 2; i < n; ++i)
mxdiv = mxdiv / arr[i];
return arr[0] / mxdiv;
}
int main()
{
int arr[] = { 100, 1000, 10, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << maxDivision(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG{
static float maxDivision(Integer arr[], int n)
{
Arrays.sort(arr, Collections.reverseOrder());
float mxdiv = arr[ 1 ];
for ( int i = 2 ; i < n; ++i)
mxdiv = mxdiv / arr[i];
return arr[ 0 ] / mxdiv;
}
public static void main(String[] args)
{
Integer arr[] = { 100 , 1000 , 10 , 2 };
int n = arr.length;
System.out.print(( int )maxDivision(arr, n));
}
}
|
Python3
def maxDivision(arr, n):
arr.sort(reverse = True )
mxdiv = arr[ 1 ]
for i in range ( 2 , n):
mxdiv = mxdiv / arr[i]
return arr[ 0 ] / mxdiv
arr = [ 100 , 1000 , 10 , 2 ]
n = len (arr)
print (maxDivision(arr, n))
|
C#
using System;
class GFG{
static float maxDivision( int []arr, int n)
{
Array.Sort(arr);
Array.Reverse(arr);
float mxdiv = arr[1];
for ( int i = 2; i < n; ++i)
mxdiv = mxdiv / arr[i];
return arr[0] / mxdiv;
}
public static void Main(String[] args)
{
int []arr = { 100, 1000, 10, 2 };
int n = arr.Length;
Console.Write(( int )maxDivision(arr, n));
}
}
|
Javascript
<script>
function maxDivision(arr, n)
{
arr.sort((a, b) => b - a);
let mxdiv = arr[1];
for (let i = 2; i < n; ++i)
mxdiv = mxdiv / arr[i];
return arr[0] / mxdiv;
}
let arr = [ 100, 1000, 10, 2 ];
let n = arr.length;
document.write(maxDivision(arr, n));
</script>
|
Time Complexity: O(N log N)
Auxiliary space: O(1)
Share your thoughts in the comments
Please Login to comment...