This problem is from HackerEarth:
The Monk learned about priority queues recently and asked his teacher for an interesting problem. So his teacher came up with a simple problem. He now has an integer array A. For each index i, he wants to find the product of the largest, second largest and the third largest integer in the range [1,i].
Note: Two numbers can be the same value-wise but they should be distinct index-wise.
Input:
- The first line contains an integer N, denoting the number of elements in the array A.
- The next line contains N space separated integers, each denoting the ith integer of the array A.
Output:
Print the answer for each index in each line. If there is no second largest or third largest number in the array A upto that index, then print "-1", without the quotes.
Constraints:
1 <= N <= 100000
0 <= A[i] <= 1000000Sample Input
5 1 2 3 4 5
Sample Output
-1 -1 6 24 60
Explanation
There are 5 integers 1,2,3,4 and 5.
- For the first two indexes, since the number of elements is less than 3, so -1 is printed.
- For the third index, the top 3 numbers are 3,2 and 1 whose product is 6.
- For the fourth index, the top 3 numbers are 4,3, and 2 whose product is 24.
- For the fifth index, the top 3 numbers are 5,4 and 3 whose product is 60.
Time Limit: 1.0 sec(s) for each input file.
Memory Limit: 256 MB
Source Limit: 1024 KB
Marking Scheme: Marks are awarded if any testcase passes.
Allowed Languages: C, CPP, CLOJURE, CSHARP, GO, HASKELL, JAVA, JAVASCRIPT, JAVASCRIPT_NODE, LISP, OBJECTIVEC, PASCAL, PERL, PHP, PYTHON, RUBY, R, RUST, SCALA
Here is my solution:
#include <iostream>
#include <limits>
#define lld long long
int n, N = 0;
using namespace std;
void max_heapify(int arr[], int n, int i){
int largest = i;
int left = 2 * i;
int right = 2*i + 1;
if(left <= n && arr[left] > arr[largest]){
largest = left;
}
if(right <= n && arr[right] > arr[largest]){
largest = right;
}
if(largest != i){
swap(arr[i], arr[largest]);
max_heapify(arr, n, largest);
}
}
void build_max_heap(int arr[], int n){
for(int i = n/2; i >=1; i--){
max_heapify(arr,n,i);
}
}
int extract_max(int arr[], int in){
if(in < 1){
throw "underflow";
}
int max = arr[1];
arr[1] = arr[in--];
max_heapify(arr, in, 1);
return max;
}
int main(){
cin >> n;
int in;
int *arr = new int[n+100];
int _1st,_2nd,_3rd;
for (int i = 1; i <= n; ++i) {
cin >> arr[i];
build_max_heap(arr, i);
lld ans;
if (i <= 2) {
cout << "-1" << endl;
}
else {
_1st = extract_max(arr, n);
_2nd = extract_max(arr, n);
_3rd = extract_max(arr, n);
ans = _1st * _2nd * _3rd;
printf("%lld\n", ans);
int p = i;
arr[p] = _1st; p--;
arr[p] = _2nd; p--;
arr[p] = _3rd;
}
}
return 0;
}
Here I'm calling the build_max_heap
for every input, because the problem demand to produce an output after each input so, I think that's causing the problem, but as far as I know, Heapify takes O(log n) time and build_max_heap
takes linear time, so it shouldn't exceed more that one second for the 4th input which is here around 1000000 input.