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.
Find the sum of all odd-length subarrays of arr.

Example 1:

Input: arr = {1,4,2,5,3}
Output: 58

Approach

Java

public class SumAllOddLenSubarrays {
    public static void main(String[] args) {
        int arr[] = { 14253 };
        System.out.println(sumOddLengthSubarrays(arr));
    }

    // function to find all the subarray of
    // odd length
    static int sumOddLengthSubarrays(int[] arr) {
        int n = arr.length;
        int ans = 0;
        for (int i = 0; i < n; i++) {
            int sum = 0;
            for (int j = i; j < n; j++) {
                sum += arr[j];
                if ((j - i) % 2 == 0)
                    ans += sum;
            }
        }
        return ans;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;


//function to find all the subarray of
//odd length
int sumOddLengthSubarrays(vector<int>& arr
{
    int n=arr.size();
    int ans=0;
    for(int i=0;i<n;i++)
        {
            int sum=0;
            for(int j=i;j<n;j++) 
            {
                sum+=arr[j];
                if((j-i)%2==0)
                      ans+=sum;
            }
        }
        return ans;
}
int main()
{
   vector<intarr = {1,4,2,5,3};
   cout<<sumOddLengthSubarrays(arr);
   return 0;
}


No comments:

Post a Comment