Sum of All Odd-Length Subarrays
Consider every contiguous stretch of arr whose length is odd (1, 3, 5, ...). Add up the sums of all those stretches, counting a stretch separately each time it occurs at a different position.
Example 1
arr [1,4,2,5,3]
returns 58
Length 1 gives 15, length 3 gives 7+11+10 = 28, length 5 gives 15: total 58.
Example 2
arr [10,11,12]
returns 66
Stretches of length 1 sum to 33, the full list adds 33: 66.
Constraints
1 <= len(arr) <= 20-20 <= arr[i] <= 20
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Arrays problems
- Third Maximum NumberEasy
- Times in the LeadEasy
- Valid Mountain ArrayEasy
- Best Rotation ScoreMedium
- Best Stretch Around a RingMedium
- Fewest Swaps to SortMedium
- Insert IntervalMedium
- Longest HillMedium