# Maximum product from array such that frequency sum of all repeating elements in product is less than or equal to 2 * k in C++

In this tutorial, we will be discussing a program to find maximum product from array such that frequency sum of all repeating elements in product is less than or equal to 2 * k.

For this we will be provided with an array and an integer k. Our task is to find the maximum product from the array given that the frequency sum of all digits must be smaller than or equal to 2 * k.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
#define ll long long int
//returning maximum product value
ll maxProd(int arr[], int n, int k) {
ll product = 1;
unordered_map<int, int> s;
sort(arr, arr + n);
for (int i = 0; i < n; i++) {
if (s[arr[i]] == 0) {
product = product * arr[i];
}
//storing values in hash map
s[arr[i]] = s[arr[i]] + 1;
}
for (int j = n - 1; j >= 0 && k > 0; j--) {
if ((k > (s[arr[j]] - 1)) && ((s[arr[j]] - 1) > 0)){
product *= pow(arr[j], s[arr[j]] - 1);
k = k - s[arr[j]] + 1;
s[arr[j]] = 0;
}
if (k <= (s[arr[j]] - 1) && ((s[arr[j]] - 1) > 0)) {
product *= pow(arr[j], k);
break;
}
}
return product;
}
int main() {
int arr[] = { 5, 6, 7, 8, 2, 5, 6, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 2;
cout << maxProd(arr, n, k);
return 0;
}

## Output

161280