VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-number-of-maximum-product-quadruples/

⇱ Find the Number of Maximum Product Quadruples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the Number of Maximum Product Quadruples

Last Updated : 12 Sep, 2022

Given an array of N positive elements, find the number of quadruples, (i, j, k, m) such that i < j < k < m such that the product aiajakam is the maximum possible.

Examples:

Input : N = 7, arr = {1, 2, 3, 3, 3, 3, 5}  
Output : 4 
 Explanation 
The maximum quadruple product possible is 135, which can be 
achieved by the following quadruples {i, j, k, m} such that aiajakam = 135:
1) a3a4a5a7
2) a3a4a6a7
3) a4a5a6a7
4) a3a5a6a7

Input : N = 4, arr = {1, 5, 2, 1} 
Output : 1 
Explanation 
The maximum quadruple product possible is 10, which can be 
achieved by the following quadruple {1, 2, 3, 4} as a1a2a3a4 = 10

Brute Force: O(n4) 

Generate all possible quadruple and count the quadruples, giving the maximum product.

Optimized Solution: It is easy to see that the product of the four largest numbers would be the maximum. So, the problem can now be reduced to finding the number of ways of selecting the four largest elements. To do so, we maintain a frequency array that stores the frequency of each element of the array. 

Suppose the largest element is X with frequency FX, then if the frequency of this element is >= 4, it is best suited to select the four elements as X, X, X, as that, given a maximum product and the number of ways to do so is FX C 4 

and if the frequency is less than 4, the number of ways to select this is 1 and now the required number of elements is 4 - FX. For the second element, say Y, the number of ways are: FX C remaining_choices. Remaining choices denotes the number of additional elements we need to select after selecting the first element. If at any time, the remaining_choices = 0, it means the quadruples are selected, so we can stop the algorithm. 

Implementation:


Output
1

Complexity Analysis:

  • Time Complexity: O(NlogN), where N is the size of the array.
  • Auxiliary Space: O(N)
Comment
Article Tags:
Article Tags: