# Find a subset with greatest geometric mean in C++

Here we have an array A with some elements. Our task is to find the subset where the geometric mean is maximum. Suppose A = [1, 5, 7, 2, 0], then the subset with greatest geometric mean will be [5, 7].

To solve this, we will follow one trick, we will not find the mean, as we know that the largest two elements will form the greatest geometric mean, so the largest two elements will be returned as subset.

## Example

#include <iostream>
using namespace std;
void largestGeoMeanSubset(int arr[], int n) {
if (n < 2) {
cout << "Very few number of elements";
return;
}
int max = INT_MIN, second_max = INT_MIN;
for (int i = 0; i < n ; i ++) {
if (arr[i] > max) {
second_max = max;
max = arr[i];
}else if (arr[i] > second_max)
second_max = arr[i];
}
cout << second_max << ", "<< max;
}
int main() {
int arr[] = {1, 5, 7, 2, 0};
int n = sizeof(arr)/sizeof(arr[0]);
largestGeoMeanSubset(arr, n);
}

## Output

5, 7

Updated on: 24-Oct-2019

104 Views

##### Kickstart Your Career

Get certified by completing the course