Maximum product from array such that frequency sum of all repeating elements in product is less than or equal to 2 * k | C ++ implementation of the approach ; Function to return the maximum product value ; To store the product ; Sort the array ; Efficiently finding product including every element once ; Storing values in hash map ; Including the greater repeating values so that product can be maximized ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll  long long int NEW_LINE 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 ] ; } 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 ; }