Problem Description
Given an array of positive integers, return the sum of all possible odd-length subarrays. A subarray is a contiguous subsequence of the array.
Key Insights
- Instead of iterating through all subarrays (which may be inefficient), determine how many odd-length subarrays each element participates in.
- For an element at index i, compute:
- left_count = number of elements (including itself) to its left, i.e. (i+1).
- right_count = number of elements (including itself) to its right, i.e. (n-i).
- The number of subarrays that include the element and have odd length is given by:
(odd_left * odd_right + even_left * even_right)
where:
- odd_left = (left_count + 1) // 2, even_left = left_count // 2
- odd_right = (right_count + 1) // 2, even_right = right_count // 2
- Multiply the element’s value by its total count from odd-length subarrays to accumulate the result.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
We use a combinatorial approach to count the number of odd-length subarrays that each element contributes to. For every index, compute the number of subarrays starting on the left and ending on the right that can include the current element. Then, use the parity counts (odd and even counts) on both sides to determine how many of these subarrays have odd length. Sum the product of each element's value with its corresponding count. This approach avoids enumerating all subarrays and runs in a single pass over the array.