|
| 1 | +/* |
| 2 | +Given an input stream of n integers the task is to insert integers to stream and |
| 3 | +print the median of the new stream formed by each insertion of x to the stream. |
| 4 | +-------------------------------------------------------------------------------- |
| 5 | +Example |
| 6 | +
|
| 7 | +Flow in stream : 5, 15, 1, 3 |
| 8 | +5 goes to stream --> median 5 (5) |
| 9 | +15 goes to stream --> median 10 (5, 15) |
| 10 | +1 goes to stream --> median 5 (5, 15, 1) |
| 11 | +3 goes to stream --> median 4 (5, 15, 1, 3) |
| 12 | +
|
| 13 | +Input: |
| 14 | +The first line of input contains an integer N denoting the no of elements of the stream. |
| 15 | +Then the next N lines contains integer x denoting the no to be inserted to the stream. |
| 16 | +
|
| 17 | +Output: |
| 18 | +For each element added to the stream print the floor of the new median in a new line. |
| 19 | +
|
| 20 | +Constraints: |
| 21 | +1<=N<=10^5+7 |
| 22 | +1<=x<=10^5+7 |
| 23 | +
|
| 24 | +Example: |
| 25 | +Input: |
| 26 | +4 |
| 27 | +5 |
| 28 | +15 |
| 29 | +1 |
| 30 | +3 |
| 31 | +Output: |
| 32 | +5 |
| 33 | +10 |
| 34 | +5 |
| 35 | +4 |
| 36 | +*/ |
| 37 | +import java.util.*; |
| 38 | +import java.lang.*; |
| 39 | +import java.io.*; |
| 40 | +class GFG |
| 41 | + { |
| 42 | + public static void main (String[] args) |
| 43 | + { |
| 44 | + //code |
| 45 | + Scanner sc=new Scanner(System.in); |
| 46 | + int n=sc.nextInt(); |
| 47 | + PriorityQueue<Integer> maxHeap=new PriorityQueue<Integer>( |
| 48 | + new Comparator<Integer> () { |
| 49 | + public int compare(Integer a, Integer b) { |
| 50 | + return b - a; |
| 51 | + } |
| 52 | + } |
| 53 | + ); |
| 54 | + PriorityQueue<Integer> minHeap=new PriorityQueue<Integer>(); |
| 55 | + int first=sc.nextInt(); |
| 56 | + int second=sc.nextInt(); |
| 57 | + if(first<second){ |
| 58 | + maxHeap.add(first); |
| 59 | + minHeap.add(second); |
| 60 | + } |
| 61 | + else{ |
| 62 | + maxHeap.add(second); |
| 63 | + minHeap.add(first); |
| 64 | + } |
| 65 | + System.out.println(first); |
| 66 | + System.out.println(((first+second))/2); |
| 67 | + for(int i=0;i<n-2;i++){ |
| 68 | + int t=sc.nextInt(); |
| 69 | + if(t<maxHeap.peek())maxHeap.add(t); |
| 70 | + else minHeap.add(t); |
| 71 | + int diff=minHeap.size()-maxHeap.size(); |
| 72 | + if(diff>1)maxHeap.add(minHeap.poll()); |
| 73 | + if(diff<-1)minHeap.add(maxHeap.poll()); |
| 74 | + diff=minHeap.size()-maxHeap.size(); |
| 75 | + if(diff==0)System.out.println((minHeap.peek()+maxHeap.peek())/2); |
| 76 | + else if(diff==1)System.out.println(minHeap.peek()); |
| 77 | + else System.out.println(maxHeap.peek()); |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments