Skip to content

Commit 9fd5ae6

Browse files
authored
Update solution.cpp
1 parent 3f0be0c commit 9fd5ae6

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,79 @@
1+
/*
2+
In this question we divide the already entered elements into 2 halves
3+
the elements in the half with smaller elemenrs go into a max heap
4+
the elememts in the half with bigger elemenrs go in min heap
5+
If there are even no of elements we use biggest element of smaller half and
6+
smaller element of bigger half to compute the median
7+
In case of odd no of elements we keep 1 extra element in the max heap or min heap
8+
and use the heap with more elements to calculate median
9+
*/
10+
#include<bits/stdc++.h>
11+
using namespace std;
112

13+
priority_queue<int, vector<int>, greater <int> > min_heap; //making a min heap
14+
priority_queue<int> max_heap; //making a max heap
15+
16+
int absh(int x){ //function to return absolute value of an int
17+
if(x>0) return x;
18+
else return (-1*x);
19+
}
20+
21+
void add(int a) //function to add a number
22+
{
23+
if( max_heap.size() && a >= max_heap.top()) //if the number is bigger than the current median
24+
min_heap.push(a); //add in the min heap
25+
else
26+
max_heap.push(a); // otherwise max heap
27+
28+
if(absh(max_heap.size() - min_heap.size()) > 1) //if the difference between the number of elements
29+
{ //larger than 1 adjust elements within the heaps to make it 0
30+
if(max_heap.size() > min_heap.size()) //if max heap has more elements transfer one to min heap
31+
{
32+
int temp = max_heap.top();
33+
max_heap.pop();
34+
min_heap.push(temp);
35+
}
36+
else //if min heap has more elements transfer it to max heap
37+
{
38+
int temp = min_heap.top();
39+
min_heap.pop();
40+
max_heap.push(temp);
41+
}
42+
}
43+
}
44+
45+
double get_median() //function to return median with current elements
46+
{
47+
int total = min_heap.size() + max_heap.size();
48+
double ret;
49+
if(total%2 == 1) //check if the no of elements is odd, if it is odd we'll have a unique median
50+
{
51+
if(max_heap.size() > min_heap.size()) //checking which of the 2 heaps has the median
52+
ret = max_heap.top();
53+
else
54+
ret = min_heap.top();
55+
}
56+
else //if it is even we have to take the mean of 2 central elements
57+
{
58+
ret = 0;
59+
if(max_heap.empty() == false)
60+
ret += max_heap.top(); //adding 1st central element
61+
if(min_heap.empty() == false)
62+
ret += min_heap.top(); //adding 2nd central element
63+
ret/=2; // taking mean of both
64+
}
65+
return ret;
66+
}
67+
68+
int main()
69+
{
70+
cout << setprecision(1) << fixed;
71+
int n, a;
72+
cin >> n;
73+
for(int i = 1; i<=n; i++)
74+
{
75+
cin >> a;
76+
add(a);
77+
cout << get_median() << endl;
78+
}
79+
}

0 commit comments

Comments
 (0)