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
Solution: DP
We would like to know how many subarrays end with arr[i] have odd or even sums.
dp[i][0] := # end with arr[i] has even sum dp[i][1] := # end with arr[i] has even sum
if arr[i] is even:
dp[i][0]=dp[i-1][0] + 1, dp[i][1]=dp[i-1][1]
else:
dp[i][1]=dp[i-1][0], dp[i][0]=dp[i-1][0] + 1
ans = sum(dp[i][1])
Time complexity: O(n) Space complexity: O(n) -> O(1)
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
classSolution{
public:
intnumOfSubarrays(vector<int>& arr) {
const int n = arr.size();
constexprintkMod=1e9+7;
// dp[i][0] # of subarrays ends with a[i-1] have even sums.
// dp[i][1] # of subarrays ends with a[i-1] have odd sums.
Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).
Example 1:
Input: low = 3, high = 7
Output: 3
Explanation: The odd numbers between 3 and 7 are [3,5,7].
Example 2:
Input: low = 8, high = 10
Output: 1
Explanation: The odd numbers between 8 and 10 are [9].
Constraints:
0 <= low <= high <= 10^9
Solution: Math
The count of odd numbers between [1, low – 1] is low / 2 e.g. low = 6, we have [1,3,5] in range [1, 5] and count is 6/2 = 3. The count of odd numbers between [1, high] is (high + 1) / 2 e.g. high = 7, we have [1,3,5,7] in range [1, 7] and count is (7+1) / 2 = 4
Then the count of odd numbers in range [low, high] = count(1, high) – count(1, low-1) e.g. in range [6, 7] we only have [7], count: 4 – 3 = 1