Count ways to select K array elements lying in a given range | 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 count of ways to select at least K elements whose values in range [ L , R ] ; Stores count of ways to select at leas K elements whose values in range [ L , R ] ; Stores count of numbers having Value lies in the range [ L , R ] ; Traverse the array ; Check 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
def calculateFactorial ( N ) : NEW_LINE INDENT fact = [ 0 ] * ( N + 1 ) NEW_LINE fact [ 0 ] = 1 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT fact [ i ] = fact [ i - 1 ] * i NEW_LINE DEDENT return fact NEW_LINE DEDENT def cntWaysSelection ( arr , N , K , L , R ) : NEW_LINE INDENT cntWays = 0 NEW_LINE cntNum = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( arr [ i ] >= L and arr [ i ] <= R ) : NEW_LINE INDENT cntNum += 1 NEW_LINE DEDENT DEDENT fact = list ( calculateFactorial ( cntNum ) ) NEW_LINE for i in range ( K , cntNum + 1 ) : NEW_LINE INDENT cntWays += fact [ cntNum ] // ( fact [ i ] * fact [ cntNum - i ] ) NEW_LINE DEDENT return cntWays NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 12 , 4 , 6 , 13 , 5 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 NEW_LINE L = 4 NEW_LINE R = 10 NEW_LINE print ( cntWaysSelection ( arr , N , K , L , R ) ) NEW_LINE DEDENT