Find the Largest triplet product in a stream in Java

In this tutorial, we are going to find the Largest triplet product in Java. This is a very basic problem and an example of heaps or priority_queue.

Priority Queue in Java or (MAX HEAP)

The priority queue is java is by default a min-heap but we can use java.util.Collections Class and convert it into a max-heap. In the given question, we will input the elements using an array which is a stream of data in real life.

We insert all the elements of the array in the max-heap or priority queue and then pop 3 elements one by one. Because the elements at the top of the priority queue will be greatest of all. So we get the first greatest element, then second greater and last third greater element. Return the product of these three values as our answer.

find Largest triplet product in a stream in Java

Let us move to the code of this problem which is very simple in Java.

import java.util.*;
import java.lang.*;
import java.io.*;
 

class Game
{
    static void ltp(int arr[], int n) {
        PriorityQueue<Integer> pq = new PriorityQueue(Collections.reverseOrder()); 
 
        for (int i = 0; i < n; i++) { 
            pq.add(arr[i]); 
 
            if (pq.size() >= 3){
                int a = pq.poll(); 
                int b = pq.poll(); 
                int c = pq.poll();   
                // Reinsert these elements as in real stream we maybe wanting
                // to get the largest triplet product at a later point of time too.
                int pro = (a*b)*c;  
                pq.add(a); 
                pq.add(b); 
                pq.add(c);
                System.out.println(pro);
            }
            else{
                System.out.println("Not possible"); 
            }
        }
    }
    
    public static void main (String[] args) throws java.lang.Exception{
         int arr[] = {1,7,3,5,9,13,2}; 
         int n = arr.length; 
         ltp(arr, n); 
    }
}
Output :
Not possible
Not possible
21
105
315
819
819

At each point of time after insert the elements we are finding the largest triplet product.

If any doubts please comment below.

Leave a Reply