Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Largest possible Subset from an Array such that no element is K times any other element in the Subset
Next article icon

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

Last Updated : 22 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] and an integer k, the task is to find the maximum product from the array such that the frequency sum of all repeating elements in the product is ≤ 2 * k, where frequency sum is the sum of frequencies of all the elements in the product that appear more than once. For example, if we choose a product 1 * 1 * 2 * 3 * 4 * 5 * 6 * 6 * 7 * 8 * 8 then the frequency sum of repeating elements in this product is 6 as the repeating elements in the product are 1, 6, and 8 (frequency of 1 + frequency of 6 + frequency of 8) = (2 + 2 + 2) = 6

Examples:

Input: arr[] = {5, 6, 7, 8, 2, 5, 6, 8}, k = 2 Output: 161280 The products can be: 5 * 5 * 7 * 8 * 8 * 2 * 6 = 134400 5 * 8 * 8 * 7 * 6 * 6 * 2 = 161280 2 * 7 * 6 * 5 * 8 * 6 * 5 = 100800 Out of which 161280 is the maximum

Input: arr[] = {1, 5, 1, 5, 4, 3, 8}, k = 2 Output: 2400

Approach:

First take the product of all the elements from the array (include only a single occurrence of the elements as a single occurrence will not affect the frequency sum). Now in order to maximize the product, sort the array and start taking all the remaining occurrences of the elements starting from the greatest element until the frequency sum doesn’t exceed 2 * k. Print the calculated product in the end.

Below is the implementation of the above approach:

C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; #define ll long long int  // Function to return the maximum product value ll maxProd(int arr[], int n, int k) {      // To store the product     ll product = 1;     unordered_map<int, int> s;      // Sort the array     sort(arr, arr + n);      for (int i = 0; i < n; i++) {         if (s[arr[i]] == 0) {              // Efficiently finding product             // including every element once             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)) {              // Including the greater repeating values             // so that product can be maximized             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; }  // Driver code 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; } 
Python
# Python3 implementation of the approach  # Function to return the maximum # product value def maxProd(arr, n, k) :      # To store the product     product = 1;     s = dict.fromkeys(arr, 0);      # Sort the array     arr.sort();      for i in range(n) :         if (s[arr[i]] == 0) :              # Efficiently finding product             # including every element once             product = product * arr[i];          # Storing values in hash map         s[arr[i]] = s[arr[i]] + 1;      j = n - 1;     while (j >= 0 and k > 0) :                  if ((k > (s[arr[j]] - 1)) and         ((s[arr[j]] - 1) > 0)) :              # Including the greater repeating values             # so that product can be maximized             product *= pow(arr[j], s[arr[j]] - 1);             k = k - s[arr[j]] + 1;             s[arr[j]] = 0;                  if (k <= (s[arr[j]] - 1) and                 ((s[arr[j]] - 1) > 0)) :             product *= pow(arr[j], k);             break;         j -= 1              return product;  # Driver code if __name__ == "__main__" :      arr = [ 5, 6, 7, 8, 2, 5, 6, 8 ];     n = len(arr) ;     k = 2;          print(maxProd(arr, n, k));      # This code is contributed by Ryuga 
Java
// Java implementation of the approach import java.util.*;  class GFG {     // Function to return the maximum product value     static long maxProd(int arr[], int n, int k)     {              // To store the product         long product = 1;         HashMap<Integer,Integer> s = new HashMap<Integer,Integer>();                  // Sort the array         Arrays.sort(arr);              for (int i = 0; i < n; i++)         {             if (s.containsKey(arr[i]) == false)             {                      // Efficiently finding product                 // including every element once                 product = product * arr[i];                                  s.put(arr[i], 1);                  }                  // Storing values in hash map             else                 s.put(arr[i],s.get(arr[i]) +1);              }              for (int j = n - 1; j >= 0 && k > 0; j--)         {             if ((k > (s.get(arr[j]) - 1)) &&                     ((s.get(arr[j]) - 1) > 0))             {                      // Including the greater repeating values                 // so that product can be maximized                 product *= Math.pow(arr[j], s.get(arr[j]) - 1);                 k = k - s.get(arr[j]) + 1;                 s.put(arr[j], 0);             }             if (k <= (s.get(arr[j]) - 1) &&                     ((s.get(arr[j]) - 1) > 0))             {                 product *= Math.pow(arr[j], k);                 break;             }         }              return product;     }          // Driver code     public static void main (String[] args)     {         int arr[] = { 5, 6, 7, 8, 2, 5, 6, 8 };         int n = arr.length;         int k = 2;         System.out.println(maxProd(arr, n, k));     } }  // This code is contributed by ihritik 
C#
// C# implementation of the approach using System; using System.Collections.Generic;  class GFG {     // Function to return the maximum product value     static long maxProd(int []arr, int n, int k)     {              // To store the product         long product = 1;         Dictionary<int, int> s = new Dictionary<int, int>();         // Sort the array         Array.Sort(arr);              for (int i = 0; i < n; i++)         {             if (!s.ContainsKey(arr[i]))             {                      // Efficiently finding product                 // including every element once                 product = product * arr[i];                      s[arr[i]] = 1;             }                  // Storing values in hash map                 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))             {                      // Including the greater repeating values                 // so that product can be maximized                 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;     }          // Driver code     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));     } }  // This code is contributed by ihritik 
JavaScript
// JavaScript implementation of the approach function maxProd(arr, n, k) { // To store the product let product = 1; let s = {};  // Sort the array arr.sort((a, b) => a - b);  for (let i = 0; i < n; i++) { if (!s[arr[i]]) { // Efficiently finding product // including every element once product *= arr[i]; } // Storing values in hash map s[arr[i]] = (s[arr[i]] || 0) + 1; }  for (let j = n - 1; j >= 0 && k > 0; j--) { if (k > s[arr[j]] - 1 && s[arr[j]] - 1 > 0) { // Including the greater repeating values // so that product can be maximized product *= Math.pow(arr[j], s[arr[j]] - 1); k -= s[arr[j]] - 1; s[arr[j]] = 0; } if (k <= s[arr[j]] - 1 && s[arr[j]] - 1 > 0) { product *= Math.pow(arr[j], k); break; } }  return product; }  // Driver code const arr = [5, 6, 7, 8, 2, 5, 6, 8]; const n = arr.length; const k = 2; console.log(maxProd(arr, n, k)); 

Output:

161280

Time Complexity: O(n logn)
Auxiliary Space: O(n)


Next Article
Largest possible Subset from an Array such that no element is K times any other element in the Subset

V

vabzcode12
Improve
Article Tags :
  • Sorting
  • Hash
  • DSA
  • Arrays
  • frequency-counting
Practice Tags :
  • Arrays
  • Hash
  • Sorting

Similar Reads

  • Maximum element in an array which is equal to its frequency
    Given an array of integers arr[] of size N, the task is to find the maximum element in the array whose frequency equals to it's value Examples: Input: arr[] = {3, 2, 2, 3, 4, 3} Output: 3 Frequency of element 2 is 2 Frequency of element 3 is 3 Frequency of element 4 is 1 2 and 3 are elements which h
    11 min read
  • Largest possible Subset from an Array such that no element is K times any other element in the Subset
    Given an array arr[] consisting of N distinct integers and an integer K, the task is to find the maximum size of a subset possible such that no element in the subset is K times any other element of the subset(i.e. no such pair {n, m} should be present in the subset such that either m = n * K or n =
    7 min read
  • Maximum elements that can be removed from front of two arrays such that their sum is at most K
    Given an integer K and two arrays A[] and B[] consisting of N and M integers, the task is to maximize the number of elements that can be removed from the front of either array according to the following rules: Remove an element from the front of either array A[] and B[] such that the value of the re
    15+ min read
  • Maximum element in an array such that its previous and next element product is maximum
    Given an array arr[] of N integers, the task is to print the largest element among the array such that its previous and next element product is maximum.Examples: Input: arr[] = {5, 6, 4, 3, 2} Output: 6 The product of the next and the previous elements for every element of the given array are: 5 -
    6 min read
  • Minimum removals required to make frequency of all remaining array elements equal
    Given an array arr[] of size N, the task is to find the minimum number of array elements required to be removed such that the frequency of the remaining array elements become equal. Examples : Input: arr[] = {2, 4, 3, 2, 5, 3}Output: 2Explanation: Following two possibilities exists:1) Either remove
    13 min read
  • Find a number K such that exactly K array elements are greater than or equal to K
    Given an array a[] of size N, which contains only non-negative elements, the task is to find any integer K for which there are exactly K array elements that are greater than or equal to K. If no such K exists, then print -1. Examples: Input: a[] = {7, 8, 9, 0, 0, 1}Output: 3Explanation:Since 3 is le
    10 min read
  • Maximize groups to be formed such that product of size of group with its minimum element is at least K
    Given an array, arr[] of length N, and an integer K. The value of the i-th element is arr[i]. The task is to find the maximum number of groups such that for each group the product of the number of elements in that group and the minimum element is at least K. Note: Every element should belong to exac
    8 min read
  • Maximize sum of K pairs made up of elements that are equidistant from both ends of the array
    Given an array arr[] consisting of N integers and an integer K, the task is to find the maximum sum of K pairs of the form (arr[i], arr[N - i - 1]), where (0 ? i ? N - 1). Examples: Input: arr[] = {2, -4, 3, -1, 2, 5}, K = 2Output: 9Explanation: All possibles pair of the form (arr[i], arr[N - i + 1]
    6 min read
  • Maximum size of subset such that product of all subset elements is a factor of N
    Given an integer N and an array arr[] having M integers, the task is to find the maximum size of the subset such that the product of all elements of the subset is a factor of N. Examples: Input: N = 12, arr[] = {2, 3, 4}Output: 2Explanation: The given array 5 subsets such that the product of all ele
    6 min read
  • Maximum length L such that the sum of all subarrays of length L is less than K
    Given an array of length N and an integer K. The task is to find the maximum length L such that all the subarrays of length L have sum of its elements less than K.Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 20 Output: 5 The only subarray of length 5 is the complete array and (1 + 2 + 3 + 4 + 5) =
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences