Number of K length subsequences with minimum sum | Function for the binomial coefficient ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Function to return the count of valid subsequences ; Sort the array ; Maximum among the minimum K elements ; Y will store the frequency of num in the minimum K elements ; cntX will store the frequency of num in the complete array ; Driver code
function binomialCoeff ( n , k ) { var C = new Array ( n + 1 ) ; for ( var i = 0 ; i < C . length ; i ++ ) { C [ i ] = new Array ( k + 1 ) ; } var i , j ; for ( i = 0 ; i <= n ; i ++ ) { for ( j = 0 ; j <= Math . min ( i , k ) ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; } } return C [ n ] [ k ] ; } function cntSubSeq ( arr , n , k ) { arr . sort ( ) ; var num = arr [ k - 1 ] ; var Y = 0 ; for ( var i = k - 1 ; i >= 0 ; i -- ) { if ( arr [ i ] == num ) Y += 1 ; } var cntX = Y ; for ( var i = k ; i < n ; i ++ ) { if ( arr [ i ] == num ) cntX += 1 ; } return binomialCoeff ( cntX , Y ) ; } var arr = [ 1 , 2 , 3 , 4 ] ; var n = arr . length ; var k = 2 ; document . write ( cntSubSeq ( arr , n , k ) ) ;