Given an array arr[] consisting of N distinctive components, the duty is to return the depend of the subsequences in an array wherein the minimal factor is X and the utmost factor is Y.
Examples:
Enter: arr[] = {2, 4, 6, 7, 5}, X = 2, Y = 5
Output: 2
Rationalization: Subsequences wherein the minimal factor is X and the utmost factor is Y are {2, 5}, {2, 4, 5}.Enter: arr[] = {2, 4, 6, 7, 5, 1, 9, 10, 11}, X = 2, Y = 7
Output: 8
Rationalization: subsequences wherein the minimal factor is X and the utmost factor is Y are {2, 4, 6, 7, 5}, {2, 4, 7, 5}, {2, 4, 6, 7}, {2, 4, 7}, {2, 6, 7, 5}, {2, 7, 5}, {2, 6, 7}, {2, 7}
Naive Method: The fundamental method to resolve the issue is as follows:
The given drawback may be solved by producing and counting all doable subsequences of the given array utilizing recursion and checking if every subsequence has the minimal factor as X and the utmost factor as Y.
Beneath is the code for the above strategy:
C++
|
Time Complexity: O(2n)
Auxiliary House: O(n)
Environment friendly Method: To resolve the issue observe the beneath concept:
We all know that the subsequence will probably be shaped will probably be within the vary (X, Y), and the system that may come for all of the subsequence within the vary (X, Y) excluding X and Y will probably be 2n the place n is the variety of components within the vary X and Y. Subsequently will return the twon as the reply.
Beneath are the steps for the above strategy:
- Initialize a counter variable say, cnt = 0 to maintain monitor of the variety of components within the vary [X, Y].
- Run a loop from i = 0 to i < n and examine if the factor lies throughout the vary (x, y),
- if (arr[i] > X && arr[i] < Y), increment the cnt variable by 1.
- Return 2cnt, which supplies us the variety of subsequences, and return 1 << cnt.
Beneath is the code for the above strategy:
C++
|
Time Complexity: O(n)
Auxiliary House: O(1)