Skip to content

Latest commit

 

History

History

1524

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Given an array of integers arr. Return the number of sub-arrays with odd sum.

As the answer may grow large, the answer must be computed modulo 10^9 + 7.

 

Example 1:

Input: arr = [1,3,5]
Output: 4
Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Odd sums are [1,9,3,5] so the answer is 4.

Example 2:

Input: arr = [2,4,6]
Output: 0
Explanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
All sub-arrays sum are [2,6,12,4,10,6].
All sub-arrays have even sum and the answer is 0.

Example 3:

Input: arr = [1,2,3,4,5,6,7]
Output: 16

Example 4:

Input: arr = [100,100,99,99]
Output: 4

Example 5:

Input: arr = [7]
Output: 1

 

Constraints:

  • 1 <= arr.length <= 10^5
  • 1 <= arr[i] <= 100

Related Topics:
Array, Math

Solution 1.

Assume sum[i] is the sum of A[0..(i - 1)], sum[0] = 0. We can get any subarray sum using sum[j] - sum[i] = A[i] + .. + A[j-1]. Given 0 < j <= N, to find how many 0 <= i < j can form odd subarray sum with j, we just need to know how many sum[i] are odd or even numbers.

If sum[j] is odd, then we use those even sum[i] to form odd subarray sum.

If sum[j] is even, then we use those odd sum[i] to form odd subarray sum.

So we just need to store how many odd sum[i] we've seen thus far in a variable odd. The number of even sum[i] is j + 1 - odd.

// OJ: https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    int numOfSubarrays(vector<int>& A) {
        long mod = 1e9+7, ans = 0, odd = 0, sum = 0;
        for (int i = 0; i < A.size(); ++i) {
            sum += A[i];
            if (sum % 2) ans = (ans + i + 1 - odd) % mod; // sum is odd, use those `i + 1 - odd` even numbers to form odd subarray sums.
            else ans = (ans + odd) % mod; // sum is even, use those `odd` odd numbers to form odd subarray sums.
            odd += sum % 2;
        }
        return ans;
    }
};