Problem
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 10^9 + 7.
Examples
Example 1:
| |
Example 2:
| |
Example 3:
| |
Solution
Method 1 - Recursion + Backtracking
graph TD;
A("[3, 3, 6, 8], tgt = 10") --> B(3) & C("[]")
B --> D("[3,3]") & E("[3]")
C --> F("[3]") & G("[]")
Time complexity - O(2^n)
Method 2 - Using Two Sum
- This problem is a variant of the Two Sum.
- In this scenario, the order of numbers in a subsequence is irrelevant; only the maximum and minimum values of the subsequence matter. Therefore, a subsequence from index i to j in the original array is equivalent to an array with the same elements and the same minimum and maximum values. For example, consider
nums = [3, 7, 6, 5]andtarget = 10. Here, the subsequence[3, 7, 6]is equivalent to the subsequence[3, 6, 7]of the sorted array[3, 5, 6, 7]. Thus, the result fornumsis the same as the result forsorted(nums). - For each index
iinsorted_nums, identify the maximum indexjsuch thatsorted_nums[i] + sorted_nums[j] <= targetandj >= i. - From
i+1toj, each element can either be included or excluded. - Therefore,
res += 2^(j-i).
Code
| |
Complexity
- ⏰ Time complexity:
O(n log n), for sorting the array.O(n)as each element is processed at most twice.
- 🧺 Space complexity:
O(n)- Auxiliary Space:
O(n)for storing the precomputed powers of 2 in the arraypows.
- Auxiliary Space: