# Gary and multiplication — Asked in Intuit and American Express Interviews

# Problem Statement :

Gary has recently learned about priority queues and is quite excited about them. He has asked his teacher for an interesting problem. So, his teacher came up with a simple problem.

The problem is that he now has an integer array ‘ARR’. For every index i, he wants to find the product of the largest, second largest and the third largest integer in the range [0, i] given that array has 0 based indexing.

You have to return the list as required.

**Sample Input:**

42 3 1 4

**Sample Output:**

`-1 -1 6 24`

# Explanation of given Test Cases :

`-1 (no second largest as well as third largest element is present)`

-1 (no third largest element is present)

6 (3 * 2 * 1)

24 (4 * 3 * 2)

# Approach :

# Priority Queue

- The idea is to work with the max priority queue.
- Insert the elements of array ‘ARR’ one by one.
- Once you add the element, extract 3 elements from the max priority queue. They will, of course, be largest (the one extracted the first time), second largest (the one extracted the second time) and third largest (the one extracted the third time).
- It should be noted that while executing point 3, one should take care of the time when the size of the priority queue will be less than 2.
- Now, all you need to do is find the product of the three numbers and print the answer.

But this would give Space complexity of O(N). So we will modify a bit.

# Using O(1) Space

- The idea is to use 3 elements. One for largest, one for second largest and one for third largest.
- Now, all we need to do is iterate the whole array while maintaining the appropriate values in the variables and keep on printing the answer.

Time complexity: O(N)

Space complexity: O(1)