For each number, we can either include it or not in a subsequence. We can use dynamic programming to keep track of the number of subsequences with even and odd sums. For each number, if we add it to an even-sum subsequence, the parity flips if the number is odd, otherwise it stays the same.
classSolution {
publicintcountOddSumSubsequences(int[] nums) {
int MOD = 1_000_000_007;
long even = 1, odd = 0;
for (int x : nums) {
if (x % 2 == 0) {
even = even * 2 % MOD;
odd = odd * 2 % MOD;
} else {
long neven = (even + odd) % MOD;
long nodd = (even + odd) % MOD;
even = neven;
odd = nodd;
}
}
return (int)((odd + MOD) % MOD);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
funcountOddSumSubsequences(nums: IntArray): Int {
val MOD = 1_000_000_007
var even = 1Lvar odd = 0Lfor (x in nums) {
if (x % 2==0) {
even = even * 2 % MOD
odd = odd * 2 % MOD
} else {
val neven = (even + odd) % MOD
val nodd = (even + odd) % MOD
even = neven
odd = nodd
}
}
return ((odd + MOD) % MOD).toInt()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defcountOddSumSubsequences(self, nums: list[int]) -> int:
MOD =10**9+7 even, odd =1, 0for x in nums:
if x %2==0:
even = even *2% MOD
odd = odd *2% MOD
else:
neven = (even + odd) % MOD
nodd = (even + odd) % MOD
even, odd = neven, nodd
return odd % MOD
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfncount_odd_sum_subsequences(nums: Vec<i32>) -> i32 {
let m =1_000_000_007;
let (mut even, mut odd) = (1i64, 0i64);
for&x in&nums {
if x %2==0 {
even = even *2% m;
odd = odd *2% m;
} else {
let neven = (even + odd) % m;
let nodd = (even + odd) % m;
even = neven;
odd = nodd;
}
}
(odd + m) asi32% m
}
}