【leetcode】1524. Number of Sub-arrays With Odd Sum
题目如下:
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: 16Example 4:
Input: arr = [100,100,99,99] Output: 4Example 5:
Input: arr = [7] Output: 1Constraints:
1 <= arr.length <= 10^5
1 <= arr[i] <= 100
解题思路:假设dp_odd[i] = v表示以第i个元素作为子数组的最后一个元素时,arr有v个和为奇数的子数组,dp_even[i] = v2 则表示,arr中有v2个和为偶数子数组。对于任意一个arr[i],如果值为奇数,那么可以和前面和为偶数的子数组形成和为奇数的子数组,一共有 dp_odd[i] = dp_even[i-1] + 1 (这里加1是因为arr[i]可以独自组成一个和为奇数的子数组),而dp_even[i] = dp_odd[i-1];同理arr[i]为偶数时原理是一样的。
代码如下:
class Solution(object): def numOfSubarrays(self, arr): """ :type arr: List[int] :rtype: int """ dp_odd = [0] * len(arr) dp_even = [0] * len(arr) if arr[0] % 2 == 0: dp_even[0] = 1 else:dp_odd[0] = 1 for i in range(1,len(arr)): if arr[i] % 2 == 0: dp_even[i] += (dp_even[i-1] + 1) dp_odd[i] += dp_odd[i-1] else: dp_even[i] += dp_odd[i-1] dp_odd[i] += (dp_even[i - 1] + 1) #print dp_even #print dp_odd return sum(dp_odd) % (10**9+7)