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.

Follow up: Could you solve this problem in O(n) time complexity?

Example 1
Inputarr = [1,4,2,5,3]
Output58
The odd-length subarrays have sums 1, 4, 2, 5, 3, 7, 11, 10, and 15, which add up to 58.
Example 2
Inputarr = [1,2]
Output3
There are only two subarrays of odd length, [1] and [2], and their sum is 3.

Constraints

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

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate