Description
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
分析
题目的意思是:给你一个数组,求其每个子数组的和为奇数的个数,这道题我暴力破解了一下,发现超时了。也没做出来,后面看了一下别人动态规划的思路,dp[i]表示的是以i为截止的新增子数组的和为奇数的数量,然后遍历数组,首先判断第0个位置的数是否为奇数,如果是dp[0]=0,否则为1,对于后面的遍历,如果是偶数,则不改变新增奇数数组的数量,dp[i]=dp[i-1],如果是奇数,则新增了dp[i]=i-dp[i-1]+1个奇数。
代码
class Solution:
def numOfSubarrays(self, arr: List[int]) -> int:
n=len(arr)
dp=[0]*n
if(arr[0]%2==1):
dp[0]=1
cnt=0
for i in range(0,len(arr)):
if(i==0):
cnt+=dp[0]
continue
elif(arr[i]%2==0):
dp[i]=dp[i-1]
else:
dp[i]=i-dp[i-1]+1
cnt=(cnt+dp[i])%(10**9+7)
return cnt