Sum of All Odd Length Subarrays
To solve this problem, we can use a simple approach of generating all possible subarrays with odd length and adding their sum.
Here is the Python solution:


In this code, we use two loops. The outer loop is to control the length of the subarray (only odd lengths are considered, hence range(1, n+1, 2)
) and the inner loop is to slide this subarray window across the given array. For each subarray, we calculate the sum of its elements and add it to the total sum. We return the total sum after traversing all possible oddlength subarrays.
Please note that this solution has time complexity of O(n^2) which is acceptable as per the problem constraints. However, there are more optimized solutions available using prefix sum and mathematical properties, if required.
The brute force solution to this problem is to generate all subarrays of the input array, calculate the sum for each, and then add up the sums of those that have an odd length.
Here is how it would look:
 Initialize a variable,
total
, to 0.  For each starting index
i
from 0 ton1
, wheren
is the length of the array: For each ending index
j
fromi
ton1
: If the length of the subarray from index
i
toj
(inclusive) is odd, calculate the sum of the elements in this subarray and add it tototal
.
 If the length of the subarray from index
 For each ending index
 Return
total
.
This solution will indeed give us the correct result, but its time complexity is O(n^3) as there are n^2 subarrays and we are spending O(n) time to calculate the sum for each. This is not an efficient approach when the size of the array is large.
The solution provided earlier is an optimized version of the brute force approach. It reduces the time complexity to O(n^2) by calculating the sums of the subarrays in constant time using the builtin sum
function. It does this by taking advantage of the fact that subarrays starting at the same index have overlapping elements.