![]() |
VOOZH | about |
Given a stream of integers represented as arr[]. For each index i from 0 to n-1, print the multiplication of the largest, second largest, and 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 onInput: arr[] = {-5, -2, 0, 3, 6, 7}
Output: -1 -1 0 0 0 126
Explanation: Fori = 2: Three elements are{-5, -2, 0}, so their product =0.
Fori = 3: Three largest elements are{-2, 0, 3}, product =0.
Fori = 4: Three largest elements are{0, 3, 6}, product =0.
Fori = 5: Three largest elements are{3, 6, 7}, product =3*6*7 = 126.Input: arr[] = {2, 2, 2, 2, 2}
Output: -1 -1 8 8 8
Explanation: Fori = 2: Three elements{2, 2, 2}, so2*2*2 = 8.
Fori = 3and onwards, the largest three elements are always{2, 2, 2}, so output remains8.
The idea is to maintain the three largest elements encountered so far using a heap data structure. For every element in the input, if fewer than three elements are available, the output is -1. Otherwise, the product of the three largest elements is calculated and stored.
Steps to implement the above idea:
-1 -1 6 24 60
The idea is to track the three largest elements encountered so far using three variables. For each element in the input, update these variables if the current element is larger than any of them. If fewer than three elements exist or the third largest is uninitialized, append -1. Otherwise, calculate the product of the three largest and store it in the result.
Steps to implement the above idea:
-1 to the result.-1 values.-1 -1 6 24 60