Sum of all subsequences of length K | C ++ implementation to find 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int fact ( int n ) ; int nCr ( int n , int r ) { return fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ; } int fact ( int n ) { int res = 1 ; for ( int i = 2 ; i <= n ; i ++ ) res = res * i ; return res ; } int sumSubsequences ( int arr [ ] , int n , int k ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } int kLengthSubSequence ; kLengthSubSequence = nCr ( n , k ) ; int ans = sum * ( ( k * kLengthSubSequence ) / n ) ; return ans ; } int main ( ) { int arr [ ] = { 7 , 8 , 9 , 2 } ; int K = 2 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << sumSubsequences ( arr , n , K ) ; return 0 ; }