1524. The number of subarrays whose sum is an odd number (C language is easy to understand)

You are given an integer array arr. Please return the number of subarrays whose sum is an odd number.

Since the answer may be very large, please return the result after modulo 10^9 + 7.

Example 1:

Input: arr = [1,3,5]
Output: 4
Explanation: All subarrays are [[1],[1,3],[1,3,5],[3],[3,5], [5]].
The sum of all subarrays is [1,4,9,3,8,5].
The odd sum includes [1,9,3,5], so the answer is 4.
Example 2:

Input: arr = [2,4,6]
Output: 0
Explanation: All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[ 6]] .
The sum of all subarrays is [2,6,12,4,10,6].
All subarray sums are even, so 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

Analysis: This question examines dynamic programming + array

We first need to know that odd + odd = even, and odd + even = odd. We can use the bit operator to judge, (arr [i ] & 1 ) == 1, if it is true, then it is an odd number, otherwise it is false.

int numOfSubarrays(int* arr, int n){
    int MOD=(int) 1e9+7;
    int odd=0,even=0,cnt=0;
        for(int i=0;i<n;i++){
              // odd 表示以当前元素 k 结尾和为奇数子数组数目
            // even 表示以当前元素 k 结尾和为偶数子数组数目
            if((arr[i]& 1) == 1){
                int t = odd;
                // 偶数 + 奇数k = 奇数              
                odd = even + 1; // k 为奇数,  {k, 偶数1+k, 偶数2 + k, ...}
                even = t;       // 奇数 + 奇数k = 偶数
            }else{
                even++;  // k 为偶数,  {k, 偶数1+k, 偶数2 + k, ...}
            }

            cnt = (cnt + odd) % MOD; 
    }
  return cnt;
}

Guess you like

Origin blog.csdn.net/zhi6fui/article/details/124261441