Count of subsequences with a sum in range [ L , R ] and difference between max and min element at least X | 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. ; Given Input ; Function Call
function numberofSubsequences ( a , L , R , X , n ) { let ans = 0 ; for ( let i = 0 ; i < ( 1 << n ) ; i ++ ) { let cnt = 0 , sum = 0 ; let minVal = Number . MAX_SAFE_INTEGER , maxVal = Number . MIN_SAFE_INTEGER ; for ( let j = 0 ; j < n ; j ++ ) { if ( ( i & ( 1 << j ) ) ) { cnt += 1 ; sum += a [ j ] ; maxVal = Math . max ( maxVal , a [ j ] ) ; minVal = Math . min ( minVal , a [ j ] ) ; } } if ( cnt >= 2 && sum >= L && sum <= R && ( maxVal - minVal >= X ) ) { ans += 1 ; } } return ans ; } let a = [ 10 , 20 , 30 , 25 ] ; let L = 40 , R = 50 , X = 10 ; let N = a . length ; document . write ( numberofSubsequences ( a , L , R , X , N ) + " " ) ;