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
using System ; using System . Collections . Generic ; class GFG { static long maxProd ( int [ ] arr , int n , int k ) { long product = 1 ; Dictionary < int , int > s = new Dictionary < int , int > ( ) ; Array . Sort ( arr ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! s . ContainsKey ( arr [ i ] ) ) { product = product * arr [ i ] ; s [ arr [ i ] ] = 1 ; } else s [ arr [ i ] ] ++ ; } for ( int j = n - 1 ; j >= 0 && k > 0 ; j -- ) { if ( ( k > ( s [ arr [ j ] ] - 1 ) ) && ( ( s [ arr [ j ] ] - 1 ) > 0 ) ) { product *= ( long ) Math . 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 *= ( long ) Math . Pow ( arr [ j ] , k ) ; break ; } } return product ; } public static void Main ( ) { int [ ] arr = { 5 , 6 , 7 , 8 , 2 , 5 , 6 , 8 } ; int n = arr . Length ; int k = 2 ; Console . WriteLine ( maxProd ( arr , n , k ) ) ; } }