Longest subsequence whose average is less than K | Function to print the length for evey query ; sort array of N elements ; Array to store average from left ; Sort array of average ; number of queries ; print answer to every query using binary search ; Driver Code ; 4 queries
function longestSubsequence ( a , n , q , m ) { a . sort ( function ( a , b ) { return a - b } ) ; let sum = 0 ; let b = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) { sum += a [ i ] ; let av = parseInt ( ( sum ) / ( i + 1 ) , 10 ) ; b [ i ] = ( av + 1 ) ; } b . sort ( function ( a , b ) { return a - b } ) ; for ( let i = 0 ; i < m ; i ++ ) { let k = q [ i ] ; let longest = upperBound ( b , 0 , n , k ) ; document . write ( " " + ( i + 1 ) + " " + longest + " " ) ; } } function upperBound ( a , low , high , element ) { while ( low < high ) { let middle = low + parseInt ( ( high - low ) / 2 , 10 ) ; if ( a [ middle ] > element ) high = middle ; else low = middle + 1 ; } return low ; } let a = [ 1 , 3 , 2 , 5 , 4 ] ; let n = a . length ; let q = [ 4 , 2 , 1 , 5 ] ; let m = q . length ; longestSubsequence ( a , n , q , m ) ;