“This is the seventh day of my participation in the First Challenge 2022.

Like it and see. Make it a habit. Wechat search [a coding] focuses on this dream discard code from text programmers.

This article is included in the technical expert training, which contains my learning route, series of articles, interview question bank, self-study materials, e-books, etc. Welcome to star ⭐ ️


The problem itself is not that difficult, but the implication is that it’s not all subarrays, it’s contiguous subarrays. The [a, b, c] subarray for [a], [b], [a, b], [c], [a, c], [b, c), (a, b, c) there is no [a, c]!!

— Leetcode

preface

Hello, I’m One, welcome to my algorithm channel.

Only do interesting algorithms, only write algorithms for interviews.

Question

1524. The number of odd subarrays that sum

Difficulty: Medium

I give you an integer array arr. Return the number of subarrays that sum to be odd.

Since the answer may be large, return the result mod 10^9 + 7.

Example 1:

Input: arr =,3,5 [1] output: 4: all the subarray to [[1], [1, 3],,3,5 [1], [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 = minus [2] output: 0 explanation: all subarray for [[2], [2, 4], [2 minus 2], [4], [4, 6], [6]]. All subarray sums are [2,6,12,4,10,6]. All subarray sums are even, so the answer is 0.

Solution

Prefixes and templates

// Compute the prefix sum
for(int i = 1; i <= n; i++){
		pre[i] = pre[i - 1] + arr[i - 1];
}
Copy the code

Code

/ * * *@authorA coding * /
// Calculate the prefix and after

for 
  if(pre [I] %2= =0?). { res+=odd; odd+1
}else{
  res+=evv;
  evv+1
}
Copy the code

The last

Thumbs up, thumbs up, and fucking thumbs up!