描述
Given an array of positive integers arr, calculate the sum of all possible odd-length subarrays.
A subarray is a contiguous subsequence of the array.
Return the sum of all odd-length subarrays of arr.
Example 1:
Input: arr = [1,4,2,5,3]
Output: 58
Explanation: The odd-length subarrays of arr and their sums are:
[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
If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58
Example 2:
Input: arr = [1,2]
Output: 3
Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.
Example 3:
Input: arr = [10,11,12]
Output: 66
Note:
1 <= arr.length <= 100
1 <= arr[i] <= 1000
解析
根据题意,只需要找出可能的奇数长度的子数组的长度,然后在 arr 中从头开始截取奇数长度的子数组并求和即可。
解答
class Solution(object):
def sumOddLengthSubarrays(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
arr_length = len(arr)
odd_max_value = arr_length if arr_length%2==0 else arr_length+1
res = 0
# 遍历可能的子数组长度
for subarray_length in range(1, odd_max_value, 2):
# 找 subarray_length 长度的子数组并求和
for index in range(arr_length-subarray_length+1):
tmp = arr[index:index+subarray_length]
res += sum(tmp)
return res
运行结果
Runtime: 52 ms, faster than 74.31% of Python online submissions for Sum of All Odd Length Subarrays.
Memory Usage: 13.5 MB, less than 18.13% of Python online submissions for Sum of All Odd Length Subarrays.
解析
举例说明此题有一定的规律可循,现在有个偶数长度的 array [1,1,2,2],他们的所有子数组如下:
1,X,X,X 子数组长度为 1
X,1,X,X 子数组长度为 1
X,X,2,X 子数组长度为 1
X,X,X,2 子数组长度为 1
1,1,X,X 子数组长度为 2
X,1,2,X 子数组长度为 2
X,X,2,2 子数组长度为 2
1,1,2,X 子数组长度为 3
X,1,2,2 子数组长度为 3
1,1,2,2 子数组长度为 4
我们只需要长度为奇数的子数组,那么只有如下:
1,X,X,X 子数组长度为 1
X,1,X,X 子数组长度为 1
X,X,2,X 子数组长度为 1
X,X,X,2 子数组长度为 1
1,1,2,X 子数组长度为 3
X,1,2,2 子数组长度为 3
要进行最后的求和操作,使用每个元素的对应次数为
2,3,3,2
可以找寻规律,在符合题意的情况下进行求和,每个元素的使用次数为 ((i+1)*(n-i)+1)/2 ,i 为元素对应在 arr 的索引,n 为 arr 数组的长度,再乘上对应的元素自身,就是最后的结果。再用奇数长度的 arr 进行举例推算规律也一样如此。
解答
class Solution(object):
def sumOddLengthSubarrays(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
res, n = 0, len(arr)
for i, a in enumerate(arr):
res += ((i + 1) * (n - i) + 1) / 2 * a
return res
运行结果
Runtime: 20 ms, faster than 98.20% of Python online submissions for Sum of All Odd Length Subarrays.
Memory Usage: 13.5 MB, less than 18.13% of Python online submissions for Sum of All Odd Length Subarrays.
原题链接:https://leetcode.com/problems/sum-of-all-odd-length-subarrays/