【leetcode】1588. Sum of All Odd Length Subarrays

题目如下:

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

Constraints:

  • 1 <= arr.length <= 100
  • 1 <= arr[i] <= 1000

解题思路:首先把计算出[0~i]区间的所有子数组的和,然后再在子数组和的结果计算奇数长度的和。

代码如下:

class Solution(object):
    def sumOddLengthSubarrays(self, arr):
        """
        :type arr: List[int]
        :rtype: int
        """
        val = [0] * len(arr)
        for i in range(len(arr)):
            if i == 0:val[i] = arr[i]
            else:val[i] = val[i-1] + arr[i]
        res = 0
        for i in range(len(arr)):
            for j in range(i,len(arr),2):
                if i == 0:res += val[j]
                else: res += (val[j] - val[i-1])

        return res

 

posted @ 2021-05-21 16:22  seyjs  阅读(80)  评论(0编辑  收藏  举报