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.
1const MOD = 1000000007;
2
3var numSubseq = function(nums, target) {
4 nums.sort((a, b) => a - b);
5 const n = nums.length;
6 const power_2 = new Array(n).fill(1);
7 for (let i = 1; i < n; i++) {
8 power_2[i] = (power_2[i - 1] * 2) % MOD;
9 }
10
11 let result = 0;
12 let left = 0, right = n - 1;
13
14 while (left <= right) {
15 if (nums[left] + nums[right] <= target) {
16 result = (result + power_2[right - left]) % MOD;
17 left++;
18 } else {
19 right--;
20 }
21 }
22 return result;
23};
24
25// Example usage:
26const nums = [3, 5, 6, 7];
27const target = 9;
28console.log(numSubseq(nums, target));
In JavaScript, precomputing power_2 array helps shorten time during the subsequence evaluation phase by readily having power values up to length n
. This strategy reduces dependency on repeatedly calculating powers within the loop, freeing resources while maintaining code logic integrity.