Skip to content

Commit b0ad97e

Browse files
authored
Create 1498. Number of Subsequences That Satisfy the Given Sum Condit… (#828)
2 parents f68760d + 55a25f7 commit b0ad97e

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
public:
3+
int numSubseq(vector<int>& nums, int target) {
4+
int mod = 1e9 + 7;
5+
long long ans = 0;
6+
sort(nums.begin(), nums.end());
7+
int n = nums.size() - 1;
8+
9+
// Precompute powers of 2 modulo mod
10+
vector<int> powers(nums.size(), 1);
11+
for (int i = 1; i < nums.size(); ++i) {
12+
powers[i] = (powers[i - 1] * 2) % mod;
13+
}
14+
15+
for (int i = 0; i <= n; i++) {
16+
int start = i, end = n, possible = -1;
17+
while (start <= end) {
18+
int mid = start + (end - start) / 2;
19+
if (nums[i] + nums[mid] <= target) {
20+
possible = mid;
21+
start = mid + 1;
22+
} else {
23+
end = mid - 1;
24+
}
25+
}
26+
27+
if (possible == -1) continue;
28+
ans = (ans + powers[possible - i]) % mod;
29+
}
30+
31+
return ans;
32+
}
33+
};

0 commit comments

Comments
 (0)