Sponsored
Sponsored
This approach involves sorting the array and then using a two pointers method to determine valid subsequences. We focus on the potential minimum and maximum values in a subsequence.
After sorting, use two pointers, one starting from the beginning of the array (for the minimum) and the other from the end (for the maximum). For each minimum, the number of valid subsequences is determined by how many elements from the minimum can pair with elements from the maximum such that their sum is less than or equal to the target. The number of subsequences can be calculated using the binary exponentiation of 2 with the distance between the two pointers.
Time Complexity: O(n log n), due to sorting the array.
Space Complexity: O(1), or O(n) if considering the space used by sorting.
1#include <stdio.h>
2#include <stdlib.h>
3#include <math.h>
4
5#define MOD 1000000007
6
This C implementation begins by sorting the nums
array using qsort
. We define a helper function power
to calculate powers of 2 modulo a large number efficiently using binary exponentiation. The main function numSubseq
then initializes two pointers left
and right
. For each iteration, if the sum of nums[left]
and nums[right]
is less than or equal to target
, it adds the number of subsequences possible between these two indices to the result. The result is returned modulo 10^9 + 7
.
This approach involves dynamic programming where pre-computed powers of 2 are used to calculate valid subsequences. Using arrays to store results dynamically avoids repetitive calculations and exploits binary indexing for faster computation on potential subsets.
The idea is to create a precompute power array of size n to store power values of 2 up to n. Iterating with this precompute allows identifying valid subsequences without recalculating powers each iteration, enhancing efficiency especially for extremely large arrays.
Time Complexity: O(n log n) for sorting. The DP preparation step is O(n).
Space Complexity: O(n) due to the power array creation.
The C version creates a precompute array, power_2
, storing powers of 2 to speed up the process. In doing so, the calculation of power values in the main loop becomes redundant, cutting down unnecessary iterations, while achieving the same correction via binary checks.