3247. Number of Subsequences with Odd Sum π
Description
Given an array nums, return the number of subsequences with an odd sum of elements.
Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: nums = [1,1,1]
Output: 4
Explanation:
The odd-sum subsequences are: [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1].
Example 2:
Input: nums = [1,2,2]
Output: 4
Explanation:
The odd-sum subsequences are: [1, 2, 2], [1, 2, 2], [1, 2, 2], [1, 2, 2].
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 109
Solutions
Solution 1: Dynamic Programming
Thinking
Count subsequences whose sum is odd. \(n\le 10^5\) forbids enumeration. Parity of the sum depends only on how many odds were taken, so two rolling states suffice.
\(f[0],f[1]\) are even-sum and odd-sum counts so far. An odd swaps the two classes and adds the singleton; an even lets each class keep or append, and the even class also gains the singleton. The answer is the final odd class.
We define \(f[0]\) to represent the number of subsequences with an even sum so far, and \(f[1]\) to represent the number of subsequences with an odd sum so far. Initially, \(f[0] = 0\) and \(f[1] = 0\).
Traverse the array \(\textit{nums}\), for each number \(x\):
If \(x\) is odd, the update rules for \(f[0]\) and \(f[1]\) are:
That is, the current number of subsequences with an even sum is equal to the previous number of subsequences with an even sum plus the number of subsequences with an odd sum concatenated with the current number \(x\); the current number of subsequences with an odd sum is equal to the previous number of subsequences with an even sum concatenated with the current number \(x\) plus the previous number of subsequences with an odd sum, plus one subsequence containing only the current number \(x\).
If \(x\) is even, the update rules for \(f[0]\) and \(f[1]\) are:
That is, the current number of subsequences with an even sum is equal to the previous number of subsequences with an even sum plus the number of subsequences with an even sum concatenated with the current number \(x\), plus one subsequence containing only the current number \(x\); the current number of subsequences with an odd sum is equal to the previous number of subsequences with an odd sum concatenated with the current number \(x\) plus the previous number of subsequences with an odd sum.
Finally, return \(f[1]\).
The time complexity is \(O(n)\), where \(n\) is the length of the array \(\textit{nums}\). The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |