Maximum product from array such that frequency sum of all repeating elements in product is less than or equal to 2 * k | 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
def maxProd ( arr , n , k ) : NEW_LINE INDENT product = 1 ; NEW_LINE s = dict . fromkeys ( arr , 0 ) ; NEW_LINE arr . sort ( ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ arr [ i ] ] == 0 ) : NEW_LINE INDENT product = product * arr [ i ] ; NEW_LINE DEDENT s [ arr [ i ] ] = s [ arr [ i ] ] + 1 ; NEW_LINE DEDENT j = n - 1 ; NEW_LINE while ( j >= 0 and k > 0 ) : NEW_LINE INDENT if ( ( k > ( s [ arr [ j ] ] - 1 ) ) and ( ( s [ arr [ j ] ] - 1 ) > 0 ) ) : NEW_LINE INDENT product *= pow ( arr [ j ] , s [ arr [ j ] ] - 1 ) ; NEW_LINE k = k - s [ arr [ j ] ] + 1 ; NEW_LINE s [ arr [ j ] ] = 0 ; NEW_LINE DEDENT if ( k <= ( s [ arr [ j ] ] - 1 ) and ( ( s [ arr [ j ] ] - 1 ) > 0 ) ) : NEW_LINE INDENT product *= pow ( arr [ j ] , k ) ; NEW_LINE break ; NEW_LINE DEDENT j -= 1 NEW_LINE DEDENT return product ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 6 , 7 , 8 , 2 , 5 , 6 , 8 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 2 ; NEW_LINE print ( maxProd ( arr , n , k ) ) ; NEW_LINE DEDENT