Count distinct median possible for an Array using given ranges of elements | Java implementation to count the number of distinct medians of an array where each array elements are given by a range ; Function to count the number of distinct medians of an array where each array elements are given by a range ; Loop to store the starting and end range in the array ; Condition to check if the length of the array is odd ; Driver Code ; Function call
import java . util . * ; import java . awt . * ; class GFG { static void solve ( int n , ArrayList < Point > vec ) { ArrayList < Integer > a = new ArrayList < > ( ) ; ArrayList < Integer > b = new ArrayList < > ( ) ; for ( Point pr : vec ) { a . add ( pr . x ) ; b . add ( pr . y ) ; } Collections . sort ( a ) ; Collections . sort ( b ) ; int left , right , ans ; if ( ( n & 1 ) != 0 ) { left = a . get ( n / 2 ) ; right = b . get ( n / 2 ) ; ans = right - left + 1 ; } else { left = ( a . get ( n / 2 ) + a . get ( n / 2 - 1 ) ) ; right = ( b . get ( n / 2 ) + b . get ( n / 2 - 1 ) ) ; ans = right - left + 1 ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int N = 3 ; ArrayList < Point > vec = new ArrayList < > ( ) ; vec . add ( new Point ( 100 , 100 ) ) ; vec . add ( new Point ( 10 , 10000 ) ) ; vec . add ( new Point ( 1 , 1000000000 ) ) ; solve ( N , vec ) ; } }