Count of subsequences with a sum in range [ L , R ] and difference between max and min element at least X | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numberofSubsequences ( int a [ ] , int L , int R , int X , int n ) { int ans = 0 ; for ( int i = 0 ; i < ( 1 << n ) ; i ++ ) { int cnt = 0 , sum = 0 ; int minVal = INT_MAX , maxVal = INT_MIN ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( i & ( 1 << j ) ) ) { cnt += 1 ; sum += a [ j ] ; maxVal = max ( maxVal , a [ j ] ) ; minVal = min ( minVal , a [ j ] ) ; } } if ( cnt >= 2 && sum >= L && sum <= R && ( maxVal - minVal >= X ) ) { ans += 1 ; } } return ans ; } int main ( ) { int a [ ] = { 10 , 20 , 30 , 25 } ; int L = 40 , R = 50 , X = 10 ; int N = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << numberofSubsequences ( a , L , R , X , N ) << endl ; return 0 ; }