Sum of all subsequences of length K | Function to find nCr ; Function that returns factorial of n ; Function for finding sum of all K length subsequences ; Calculate the sum of array ; Calculate nCk ; Return the final result ; Driver code
function nCr ( n , r ) { return fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ; } function fact ( n ) { var res = 1 ; for ( var i = 2 ; i <= n ; i ++ ) res = res * i ; return res ; } function sumSubsequences ( arr , n , k ) { var sum = 0 ; for ( var i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } var kLengthSubSequence ; kLengthSubSequence = nCr ( n , k ) ; var ans = sum * ( ( k * kLengthSubSequence ) / n ) ; return ans ; } var arr = [ 7 , 8 , 9 , 2 ] ; var K = 2 ; var n = arr . length ; document . write ( sumSubsequences ( arr , n , K ) ) ;