1498. Number of Subsequences That Satisfy the Given Sum Condition
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 than target
.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: nums = [3,5,6,7], target = 9
Output: 4
Explanation: There are 4 subsequences that satisfy the condition.
[3] -> Min value + max value <= target (3 + 3 <= 9)
[3,5] -> (3 + 5 <= 9)
[3,5,6] -> (3 + 6 <= 9)
[3,6] -> (3 + 6 <= 9)
Example 2:
Input: nums = [3,3,6,8], target = 10
Output: 6
Explanation: There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]
Example 3:
Input: nums = [2,3,3,4,6,7], target = 12
Output: 61
Explanation: There are 63 non-empty subsequences, two of them don't satisfy the condition ([6,7], [7]).
Number of valid subsequences (63 - 2 = 61).
Example 4:
Input: nums = [5,2,4,1,7,6,8], target = 16
Output: 127
Explanation: All non-empty subset satisfy the condition (2^7 - 1) = 127
Constraints:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^6
1 <= target <= 10^6
题目:给你一个整数数组 nums
和一个整数 target
。请你统计并返回 nums
中能满足其最小元素与最大元素的 和 小于或等于 target
的 非空 子序列的数目。
思路:参考lee215。对于排序后的数组nums
,当最小值nums[i]
与最大值nums[j]
的和小于target
时,在区间[i,...,j]
中的所有组合均满足题目的要求,为了不重复,因此每次都先确定nums[i]
,而在[i+1,...,j]
中的每个元素都可选可不选,即包含nums[i]
的所有符合条件的组合共有2^(j-i+1-1)
种。
工程代码下载
class Solution {
public:
int numSubseq(vector<int>& nums, int target) {
int n = nums.size();
int mod = 1e9 + 7;
vector<int> pow(n, 1);
for(int i = 1; i < n; ++i)
pow[i] = (pow[i-1] * 2) % mod;
sort(nums.begin(), nums.end());
int l = 0, r = n - 1, res = 0;
while(l <= r){
if(nums[l] + nums[r] > target)
--r;
else
res = (res + pow[r-l++]) % mod;
}
return res;
}
};