Open In App

Largest triplet product in a stream

Last Updated : 15 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a stream of integers represented as arr[]. For each index i from 0 to n-1, print the multiplication of largest, second largest, third largest element of the subarray arr[0…i]. If i < 2 print -1. 

Examples: 

Input : arr[] = {1, 2, 3, 4, 5}
Output :-1
        -1
         6
         24
         60
Explanation : for i = 2 only three elements 
are there {1, 2, 3} so answer is 6. For i = 3
largest three elements are {2, 3, 4} their
product is 2*3*4 = 24 ....so on            

We will use priority queue here. 

  1. Insert arr[i] in the priority queue
  2. As the top element in priority queue is largest so pop it and store it as x. Now the top element in the priority queue will be the second largest element in subarray arr[0…i] pop it and store as y. Now the top element is third largest element in subarray arr[0…i] so pop it and store it as z.
  3. Print x*y*z
  4. Reinsert x, y, z.

Below is the implementation of the above approach:

C++




// C++ implementation of largest triplet
// multiplication
#include <bits/stdc++.h>
using namespace std;
 
// Prints the product of three largest numbers
// in subarray arr[0..i]
void LargestTripletMultiplication(int arr[], int n)
{
    // call a priority queue
    priority_queue<int> q;
 
    // traversing the array
    for (int i = 0; i < n; i++) {
        // pushing arr[i] in the array
        q.push(arr[i]);
 
        // if less than three elements are present
        // in array print -1
        if (q.size() < 3)
            cout << "-1" << endl;
        else {
            // pop three largest elements
            int x = q.top();
            q.pop();
            int y = q.top();
            q.pop();
            int z = q.top();
            q.pop();
 
            // Reinsert x, y, z in priority_queue
            int ans = x * y * z;
            cout << ans << endl;
            q.push(x);
            q.push(y);
            q.push(z);
        }
    }
    return;
}
 
// Driver Function
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
    LargestTripletMultiplication(arr, n);
    return 0;
}


Java




// Java implementation of largest triplet
// multiplication
import java.util.Collections;
import java.util.PriorityQueue;
 
class GFG {
 
    // Prints the product of three largest numbers
    // in subarray arr[0..i]
    static void LargestTripletMultiplication(int arr[], int n)
    {
        // call a priority queue
        PriorityQueue<Integer> q = new PriorityQueue(Collections.reverseOrder());
 
        // traversing the array
        for (int i = 0; i < n; i++) {
            // pushing arr[i] in array
            q.add(arr[i]);
 
            // if less than three elements are present
            // in array print -1
            if (q.size() < 3)
                System.out.println("-1");
            else {
                // pop three largest elements
                int x = q.poll();
                int y = q.poll();
                int z = q.poll();
 
                // Reinsert x, y, z in priority_queue
                int ans = x * y * z;
                System.out.println(ans);
                q.add(x);
                q.add(y);
                q.add(z);
            }
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 4, 5 };
        int n = arr.length;
        LargestTripletMultiplication(arr, n);
    }
}
 
// This code is contributed by shubham96301


Python3




# Python3 implementation of largest triplet
# multiplication
from queue import PriorityQueue
 
# Prints the product of three largest
# numbers in subarray arr[0..i]
def LargestTripletMultiplication(arr, n):
     
    # Call a priority queue
    q = PriorityQueue()
 
    # Traversing the array
    for i in range(n):
         
        # Pushing -arr[i] in array
        # to get max PriorityQueue
        q.put(-arr[i])
 
        # If less than three elements
        # are present in array print -1
        if (q.qsize() < 3):
            print(-1)
        else:
             
            # pop three largest elements
            x = q.get()
            y = q.get()
            z = q.get()
 
            # Reinsert x, y, z in
            # priority_queue
            ans = x * y * z
             
            print(-ans)
             
            q.put(x);
            q.put(y);
            q.put(z);
 
# Driver Code
if __name__ == '__main__':
  
    arr = [ 1, 2, 3, 4, 5 ]
    n = len(arr)
     
    LargestTripletMultiplication(arr, n)
     
# This code is contributed by math_lover


C#




// C# implementation of largest triplet
// multiplication
using System;
using System.Collections.Generic;
public class GFG {
 
  // Prints the product of three largest numbers
  // in subarray arr[0..i]
  static void LargestTripletMultiplication(int []arr, int n)
  {
    // call a priority queue
    List<int> q = new List<int>();
 
    // traversing the array
    for (int i = 0; i < n; i++)
    {
 
      // pushing arr[i] in array
      q.Add(arr[i]);
      q.Sort();
      q.Reverse();
 
      // if less than three elements are present
      // in array print -1
      if (q.Count < 3)
        Console.WriteLine("-1");
      else
      {
 
        // pop three largest elements
        int x = q[0];
        int y = q[1];
        int z = q[2];
        q.RemoveRange(0, 3);
 
        // Reinsert x, y, z in priority_queue
        int ans = x * y * z;
        Console.WriteLine(ans);
        q.Add(x);
        q.Add(y);
        q.Add(z);
      }
    }
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    int []arr = { 1, 2, 3, 4, 5 };
    int n = arr.Length;
    LargestTripletMultiplication(arr, n);
  }
}
 
 
// This code is contributed by Rajput-Ji


Javascript




<script>
// javascript implementation of largest triplet
// multiplication
    // Prints the product of three largest numbers
    // in subarray arr[0..i]
    function LargestTripletMultiplication(arr , n) {
        // call a priority queue
        var q = [];
 
        // traversing the array
        for (i = 0; i < n; i++) {
            // pushing arr[i] in array
            q.push(arr[i]);
q.sort();
               
            // if less than three elements are present
            // in array print -1
            if (q.length < 3)
                document.write("-1<br/>");
            else {
                // pop three largest elements
                q.sort();
              
                var x = q.pop();
                var y = q.pop();
                var z = q.pop();
 
                // Reinsert x, y, z in priority_queue
                var ans = x * y * z;
                document.write(ans+"<br/>");
                q.push(x);
                q.push(y);
                q.push(z);
                q.sort();
                q.reverse();
            }
        }
    }
 
    // Driver code
     
        var arr = [ 1, 2, 3, 4, 5 ];
        var n = arr.length;
        LargestTripletMultiplication(arr, n);
 
// This code contributed by umadevi9616
</script>


Output

-1
-1
6
24
60

Time Complexity: O(N * log N ).
Auxiliary Space: O(N), N is the length of the array.

 



Previous Article
Next Article

Similar Reads

Largest lexicographic triplet from a given Array that forms a triangle
Given an array arr[], the task is to find the lexicographically largest triplet in that array that can form a triangle. If no such triplet exists, print -1.Example: Input: arr[] = { 4, 2, 10, 3, 5 } Output: 3 4 5 Explanation: The lexicographically largest triplet is (4, 5, 10). But it does not form a triangle. The next lexicographically largest tri
5 min read
Find distinct integers for a triplet with given product
Given an integer X, the task is to find the three distinct integers greater than 1 i.e. A, B and C such that (A * B * C) = X. If no such triplet exists then print -1.Examples: Input: X = 64 Output: 2 4 8 (2 * 4 * 8) = 64Input: X = 32 Output: -1 No such triplet exists. Approach: Suppose we have a triplet (A, B, C). Notice that, for their product to
7 min read
Maximum product of a triplet (subsequence of size 3) in array
Given an integer array, find a maximum product of a triplet in the array. Examples: Input: [10, 3, 5, 6, 20]Output: 1200Explanation: Multiplication of 10, 6 and 20 Input: [-10, -3, -5, -6, -20]Output: -90 Input: [1, -4, 3, -6, 7, 0]Output: 168 Naive Approach: A simple solution is to check for every triplet using three nested loops. Below is its imp
15+ min read
Java Program to Find the K'th largest element in a stream
Given an infinite stream of integers, find the k'th largest element at any point of time.Example: Input: stream[] = {10, 20, 11, 70, 50, 40, 100, 5, ...} k = 3 Output: {_, _, 10, 11, 20, 40, 50, 50, ...} Extra space allowed is O(k). Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. We have discussed different appro
4 min read
C++ Program to Find the K'th largest element in a stream
Given an infinite stream of integers, find the k'th largest element at any point of time.Example: Input:stream[] = {10, 20, 11, 70, 50, 40, 100, 5, ...}k = 3Output: {_, _, 10, 11, 20, 40, 50, 50, ...} Extra space allowed is O(k). Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. We have discussed different approach
7 min read
K'th largest element in a stream
Given an infinite stream of integers, find the Kth largest element at any point of time. Note: Here we have a stream instead of a whole array and we are allowed to store only K elements. Examples: Input: stream[] = {10, 20, 11, 70, 50, 40, 100, 5, . . .}, K = 3Output: {_, _, 10, 11, 20, 40, 50, 50, . . .} Input: stream[] = {2, 5, 1, 7, 9, . . .}, K
14 min read
Generate a pythagoras triplet from a single integer
Given a single integer n [Tex]\in [/Tex][1, 1000000000], generate a Pythagoras triplet that includes n as one of its sides if possible. Examples : Input : 22 Output : Pythagoras Triplets exist i.e. 22 120 122 Input : 4 Output : Pythagoras Triplets exist i.e. 4 3 5 Input : 2 Output : No Pythagoras Triplet exists Explanation: Definition: "Pythagorean
6 min read
Prime Triplet
Prime Triplet is a set of three prime numbers of the form (p, p+2, p+6) or (p, p+4, p+6). This is the closest possible grouping of three prime numbers, since one of every three sequential odd numbers is a multiple of three, and hence not prime (except for 3 itself) except (2, 3, 5) and (3, 5, 7). Examples : Input : n = 15 Output : 5 7 11 7 11 13 In
8 min read
Pythagorean Triplet with given sum
A Pythagorean Triplet is a set of natural numbers such that a &lt; b &lt; c, for which a^2 + b^2 = c^2. For example, 3^2 + 4^2 = 5^2.Given a number n, find a Pythagorean Triplet with sum as given n. Examples : Input : n = 12Output : 3, 4, 5Note that 3, 4 and 5 is a Pythagorean Triplet with sum equal to 12. Input : n = 4.Output : No TripletThere doe
6 min read
Finding a Non Transitive Co-prime Triplet in a Range
Given L and R, find a possible non-transitive triplet (a, b, c) such that pair (a, b) is co-prime and pair (b, c) is co-prime but (a, c) is not co-prime. Eg: (2, 5, 6) is a non-transitive triplet as pair (2, 5) is co-prime and pair (5, 6) is co-prime but pair (2, 6) is not co-prime. Examples: Input : L = 2, R = 10 Output : a = 4, b = 7, c = 8 is on
15+ min read
Article Tags :
Practice Tags :