xinyu04

导航

LeetCode 1588 Sum of All Odd Length Subarrays 前缀和

Given an array of positive integers arr, return the sum of all possible odd-length subarrays of arr.

A subarray is a contiguous subsequence of the array.

Solution

求所有奇数长度子序列的和。所以维护一个前缀和以后,我们只需要遍历间隔即可

点击查看代码
class Solution {
private:
    int pref[102];
    int sft[102];
    int ans=0;
public:
    int sumOddLengthSubarrays(vector<int>& arr) {
        int n = arr.size();
        for(int i=0;i<n;i++)sft[i+1]=arr[i];
        for(int i=1;i<=n;i++)pref[i]=pref[i-1]+sft[i];
        ans+=pref[n];
        int gap = 3;
        while(n>=gap){
            for(int i=gap;i<=n;i++){
                ans+= pref[i]-pref[i-gap];
            }
            gap+=2;
        }
        return ans;
    }
};

posted on 2022-09-15 17:22  Blackzxy  阅读(9)  评论(0编辑  收藏  举报