Problem Description
Given an array of integers nums and an integer target, count the number of non-empty subsequences such that the sum of the minimum and maximum elements in each subsequence is less than or equal to target. Since the result can be very large, return the answer modulo 10^9 + 7.
Key Insights
- Sort the array to efficiently identify valid minimum and maximum pairs.
- Use the two-pointers technique with one pointer at the beginning and one at the end.
- When a valid pair (nums[left] + nums[right] <= target) is found, every combination of the elements between these pointers forms a valid subsequence.
- Precompute powers of 2 to quickly compute the number of valid combinations.
- Use modulo operations to manage large numbers.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting, plus O(n) for the two-pointer scan. Space Complexity: O(n) for the precomputed powers array.
Solution
Start by sorting the nums array. Then, initialize two pointers: left at the beginning and right at the end. For every valid pair where nums[left] + nums[right] <= target, calculate the number of subsequences that can be formed using the elements between left and right, which is 2^(right - left) (using precomputed powers of 2 to speed up the process). Add this number to the result and move the left pointer; if the pair is not valid, move the right pointer instead. Continue until the pointers cross.