zoukankan      html  css  js  c++  java
  • 【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
  • 相关阅读:
    学习进度
    毕设进度
    学习进度
    毕设进度
    学习进度
    学习进度
    第一周冲刺评论总结&&针对评论总结的改进
    第一阶段成果展示
    团队冲刺--Seven
    团队冲刺--six
  • 原文地址:https://www.cnblogs.com/seyjs/p/14794315.html
Copyright © 2011-2022 走看看