LeetCode每日一题(2021.8.29)【EASY】
给你一个正整数数组 arr ,请你计算所有可能的奇数长度子数组的和。
子数组 定义为原数组中的一个连续子序列。 返回 arr 中 所有奇数长度子数组的和 。
示例 1:
输入:arr = [1,4,2,5,3]
输出:58
解释:所有奇数长度子数组和它们的和为:
[1] = 1
[4] = 4
[2] = 2
[5] = 5
[3] = 3
[1,4,2] = 7
[4,2,5] = 11
[2,5,3] = 10
[1,4,2,5,3] = 15
我们将所有值求和得到 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-all-odd-length-subarrays
class odd_sum():
def sumOddLengthSubarrays(self,arr):
n = len(arr)
res = 0
for i in range(n):
j = 1
while i+j <= n:
nums = arr[i:i+j]
res += sum(nums)
j += 2
return res
arr = [10,11,12]
odds = odd_sum()
odd_s = odds.sumOddLengthSubarrays(arr)