Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Sum of All Odd Length Subarrays

XPChallenge Points: 10
levelLevel: Easy

A positive integer array arr is given. Your task is to compute the total sum of all subarrays that have odd lengths.
A subarray is a sequence of consecutive elements taken from the array.
You must consider every possible subarray, but only add those whose size is odd.

Example 1:

Input: arr = [2, 3, 5]

Output: 21

Explanation:

Odd-length subarrays are: [2] = 2 [3] = 3 [5] = 5 [2,3,5] = 10 Total = 2 + 3 + 5 + 10 = 21

Example 2:

Input: arr = [1, 6, 4, 7]

Output: 66

Explanation:

Odd-length subarrays: Single: 1, 6, 4, 7 Three-length: [1,6,4] = 11, [6,4,7] = 17 Full 4-length (ignored, even) Sum = 1 + 6 + 4 + 7 + 11 + 17 = 46

Example 3:

Input: arr = [5]

Output: 5

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result