LeetCode 3247: Number of Subsequences with Odd Sum Solution

Master LeetCode problem 3247 (Number of Subsequences with Odd Sum), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

3247. Number of Subsequences with Odd Sum

Problem Explanation

Explanation:

To solve this problem, we can use dynamic programming. We can iterate over the array and for each element, we can either include it in a subsequence or not include it. We can keep track of the count of subsequences ending at the current element with an even sum and the count of subsequences ending at the current element with an odd sum.

For each element, we can update the count of subsequences with even and odd sums based on the current element. At the end, we sum up all the subsequences with odd sums as our final result. :

Solution Code

class Solution {
    public int numOfSubarrays(int[] nums) {
        int mod = (int)1e9 + 7;
        long even = 1, odd = 0, res = 0, sum = 0;
        
        for (int num : nums) {
            sum += num;
            if (sum % 2 == 0) {
                even++;
            } else {
                res = (res + even) % mod;
                odd++;
            }
        }
        
        return (int)res;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3247 (Number of Subsequences with Odd Sum)?

This page provides optimized solutions for LeetCode problem 3247 (Number of Subsequences with Odd Sum) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3247 (Number of Subsequences with Odd Sum)?

The time complexity for LeetCode 3247 (Number of Subsequences with Odd Sum) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3247 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3247 in Java, C++, or Python.

Back to LeetCode Solutions