Count of subsequences with a sum in range [ L , R ] and difference between max and min element at least X | Python3 program for the above approach ; Function to find the number of subsequences of the given array with a sum in range [ L , R ] and the difference between the maximum and minimum element is at least X ; Initialize answer as 0 ; Creating mask from [ 0 , 2 ^ n - 1 ] ; Stores the count and sum of selected elements respectively ; Variables to store the value of Minimum and maximum element ; Traverse the array ; If the jth bit of the ith mask is on ; Add the selected element ; Update maxVal and minVal value ; Check if the given conditions are true , increment ans by 1. ; Driver Code ; Given Input ; Function Call
import sys NEW_LINE def numberofSubsequences ( a , L , R , X , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , ( 1 << n ) , 1 ) : NEW_LINE INDENT cnt = 0 NEW_LINE sum = 0 NEW_LINE minVal = sys . maxsize NEW_LINE maxVal = - sys . maxsize - 1 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( ( i & ( 1 << j ) ) ) : NEW_LINE INDENT cnt += 1 NEW_LINE sum += a [ j ] NEW_LINE maxVal = max ( maxVal , a [ j ] ) NEW_LINE minVal = min ( minVal , a [ j ] ) NEW_LINE DEDENT DEDENT if ( cnt >= 2 and sum >= L and sum <= R and ( maxVal - minVal >= X ) ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 10 , 20 , 30 , 25 ] NEW_LINE L = 40 NEW_LINE R = 50 NEW_LINE X = 10 NEW_LINE N = len ( a ) NEW_LINE print ( numberofSubsequences ( a , L , R , X , N ) ) NEW_LINE DEDENT