
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find 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
Advertisements