[LeetCode] Number of Subsequences That Satisfy the Given Sum Condition

1498. Number of Subsequences That Satisfy the Given Sum Condition

You are given an array of integers nums and an integer target.

Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 1e9 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
long long mod = 1e9 + 7;
long long modpow(long long n, int x) {
if(x == 1) return n;
long long res = modpow(n, x>>1);
res = (res * res) % mod;
return x & 1 ? (res * n) % mod : res;
}
public:
int numSubseq(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int l = 0, r = 0;
long long res = 0;
bool flag = 1;
for(; r < nums.size() and nums[l] + nums[r] <= target; r++) {}
r--;
while(l <= r) {
if(flag) {
res = (res + modpow(2, r - l + 1) - 1) % mod;
for(; l <= r and nums[l] + nums[r] <= target; l++) {}
flag = 0;
} else {
res = (res - modpow(2, r - l + 1) + 1 + mod) % mod;
for(; l <= r and nums[l] + nums[r] > target; r--) {}
flag = 1;
}
}
return res % mod;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/29/PS/LeetCode/number-of-subsequences-that-satisfy-the-given-sum-condition/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.