Talentd
FleetCode

3247. Number of Subsequences with Odd Sum

Medium47.6% acceptancePremium elsewhere, free here

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 <= 105
  • 1 <= nums[i] <= 109

Hints open one at a time

Hint 1
Define dp[i][0] as the answer for the subarray [0, i].
Hint 2
Similarly define dp[i][1] as the answer for the subarray [0, i] if we wanted to count even-sum subsequences.
Hint 3
If nums[i] is odd, dp[i][x] = 2i.
Hint 4
Otherwise, dp[i][x] = dp[i - 1][x] * 2.
Hint 5
dp[0][1] = 1 if nums[0] is odd, and 0 otherwise.
Hint 6
dp[0][0] = 2 if nums[0] is even, and 1 otherwise (since an empty subsequence has an even sum).
8:52
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
[1,1,1]
Input
[1,2,2]
Your code is saved on this device.Solution