[leetcode] 1524. Number of Sub-arrays With Odd Sum

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

参考文献

[LeetCode] My Python, java Solutions DP

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值