Count ways to select K array elements lying in a given range | C ++ program to implement the above approach ; Function to calculate factorial of all the numbers up to N ; Factorial of 0 is 1 ; Calculate factorial of all the numbers upto N ; Calculate factorial of i ; Function to find the count of ways to select at least K elements whose values in range [ L , R ] ; Stores count of ways to select at least K elements whose values in range [ L , R ] ; Stores count of numbers having value lies in the range [ L , R ] ; Traverse the array ; Checks if the array elements lie in the given range ; Update cntNum ; Stores factorial of numbers upto N ; Calculate total ways to select at least K elements whose values lies in [ L , R ] ; Update cntWays ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > calculateFactorial ( int N ) { vector < int > fact ( N + 1 ) ; fact [ 0 ] = 1 ; for ( int i = 1 ; i <= N ; i ++ ) { fact [ i ] = fact [ i - 1 ] * i ; } return fact ; } int cntWaysSelection ( int arr [ ] , int N , int K , int L , int R ) { int cntWays = 0 ; int cntNum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] >= L && arr [ i ] <= R ) { cntNum ++ ; } } vector < int > fact = calculateFactorial ( cntNum ) ; for ( int i = K ; i <= cntNum ; i ++ ) { cntWays += fact [ cntNum ] / ( fact [ i ] * fact [ cntNum - i ] ) ; } return cntWays ; } int main ( ) { int arr [ ] = { 12 , 4 , 6 , 13 , 5 , 10 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; int L = 4 ; int R = 10 ; cout << cntWaysSelection ( arr , N , K , L , R ) ; }