Number of Subsequences That Satisfy the Given Sum Condition
Count the subsequences of an array whose smallest plus largest number is at most a target.
You are given an array of integers numstargettarget
Example 1
Output: 4
Explanation: [3], [3, 5], [3, 6] and [3, 5, 6].
Example 2
Output: 6
Explanation: [3], [3], [3, 3], [3, 6], [3, 6] and [3, 3, 6]. Equal numbers at different positions count as different subsequences.
Example 3
Output: 61
Explanation: of the 63 subsequences, only [6, 7] and [7] fail.
The Idea
Look at Example 1. Each of the four numbers in [3, 5, 6, 7][3, 5, 6][5, 6]
Checking all 15 is easy here, but 30 numbers already give more than a billion choices. Can we count the good subsequences without listing them?
Start with what the condition ignores: the order. The smallest and largest of the chosen numbers are the same whichever order they come in. So we may sort the array first. Sorting moves the numbers, but every choice of positions before sorting matches one choice after it, with the same numbers. The array in Example 1 happens to be sorted already.
In a sorted array, the smallest number of a choice is simply the leftmost one picked. So take the possible smallest numbers one at a time. Which subsequences have 3 as their smallest number? 3 must be in. Then the largest number can be at most 9 - 3 = 6, so 7 is out, because 3 + 7 = 10. The 5 and the 6 are free to be in or out. Look at the picture below.
Two markers mark the range. leftrightleftright
So we never need to list the subsequences. For each smallest number, every number after leftrightright - left
Solution Approach
Turning that idea into code means settling three things: how to find rightleft
Finding the largest partner
How do we find rightleft
There is a faster way. As leftrightrightnums[left] + nums[right]target
- If the sum is at most
, add 2right - left to the count and movetarget one place right.left - Otherwise
is too big even fornums[right] . The numbers afternums[left] are only larger, so it is too big for them too. Moveleft one place left.right
Each step moves one marker, so the whole walk takes at most n steps. Walking two markers through a sorted array like this is called the two-pointer technique.
The walk goes on while left <= righttarget
Counting each subsequence once
What happens with equal numbers, as in Example 2? Sorted, it reads 3, 3, 6, 8. With leftrightleft
So every subsequence is counted exactly once, under the leftmost position it uses, even when the array holds equal numbers.
Powers of two and the remainder
How big can 2right - left get? With 100 numbers it can reach 299, far past the largest long
So the powers go into an array pow2int
Java Solution
The method numSubseq
- First, sort the input array with
, so the smallest number of any choice is its leftmost one.Arrays.sort(nums) - Keep 1,000,000,007 in
. Build the arraymod with one entry per number:pow2 is 1, and each later entry is the one before it times 2, modulopow2[0] .mod - Set
to 0, putcount on the first position andleft on the last, and start aright loop that runs as long aswhile .left <= right - Inside the loop, if
is at mostnums[left] + nums[right] , addtarget topow2[right - left] , modulocount , and movemod one place right. Otherwise, moveleft one place left.right - When the loop ends, return
.count
The main
import java.util.Arrays;
public class NumberOfSubsequencesThatSatisfyTargetSumCondition {
public static int numSubseq(int[] nums, int target) {
final int mod = 1000000007;
int n = nums.length;
Arrays.sort(nums);
int[] pow2 = new int[n];
pow2[0] = 1;
for (int i = 1; i < n; i++) {
pow2[i] = pow2[i - 1] * 2 % mod;
}
int count = 0;
int left = 0;
int right = n - 1;
while (left <= right) {
if (nums[left] + nums[right] <= target) {
// nums[left] is the smallest; any values from left + 1 to right may join it
count = (count + pow2[right - left]) % mod;
left++;
} else {
right--; // nums[right] is too big even with nums[left]
}
}
return count;
}
public static void main(String[] args) {
System.out.println(numSubseq(new int[] {3, 5, 6, 7}, 9));
System.out.println(numSubseq(new int[] {3, 3, 6, 8}, 10));
System.out.println(numSubseq(new int[] {2, 3, 3, 4, 6, 7}, 12));
System.out.println(numSubseq(new int[] {7, 6, 5, 3}, 9));
System.out.println(numSubseq(new int[] {5}, 10));
System.out.println(numSubseq(new int[] {6}, 10));
int[] ones = new int[100];
Arrays.fill(ones, 1);
System.out.println(numSubseq(ones, 2));
}
}
Running it prints:
4
6
61
4
1
0
976371284
The first three lines, 4661[7, 6, 5, 3][5][6]
The last line is the 100 ones. Any choice of them has 1 + 1 = 2, so all 2100 - 1 subsequences count. That number has 31 digits, and 976371284 is its remainder after dividing by 1,000,000,007, which a check with BigInteger
Why build pow2(long) Math.pow(2, k) % modMath.powdoubledoublelongLong.MAX_VALUE
The original implementation,
Complexity
The work is the sort, one loop to fill pow2
- Time: O(n log n), where n is the length of the array.
takes O(n log n). FillingArrays.sort takes n steps, and every pass of thepow2 loop moveswhile orleft , so it ends after at most n passes.right - Space: O(n). The
array holds n powers of two. The input is sorted in place, and the markers and the count are single numbers.pow2
Moving two markers through a sorted array by comparing a sum with a target is also the core of