Skip to content

Instantly share code, notes, and snippets.

@kocko
Created January 17, 2019 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kocko/2e0dd038bea14a8b26fdf73901d1d15c to your computer and use it in GitHub Desktop.
Save kocko/2e0dd038bea14a8b26fdf73901d1d15c to your computer and use it in GitHub Desktop.
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;
class GFG {
private PriorityQueue<Integer> min = new PriorityQueue<>(), max = new PriorityQueue<>(Comparator.reverseOrder());
public int findRunningMedian(int a) {
min.add(a);
max.add(min.poll());
if (max.size() - min.size() > 1) {
min.add(max.poll());
}
return (min.size() == max.size()) ? (max.peek() + min.peek()) / 2 : min.peek();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
GFG instance = new GFG();
while (n-- > 0) {
int next = sc.nextInt();
int median = instance.findRunningMedian(next);
System.out.println(median);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment