[leetcode] 718. Maximum Length of Repeated Subarray
896
2022-08-23
[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: 4Explanation: 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: 0Explanation: 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^51 <= 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
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~