Problem
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.
Examples
Example 1:
| |
Example 2:
| |
Example 3:
| |
Solution
Method 1 - Naive
To solve this problem, we can use a direct approach of iterating through the array and summing all possible odd-length subarrays.
- For each possible starting index of the subarray, compute the sums of all odd-length subarrays starting from that index.
- Incrementally count subarrays with lengths 1, 3, 5, etc., while they are within the bounds of the array.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n^3), wherenis the length of the array. This is because we need to iterate through starting indices and subarray lengths. - 🧺 Space complexity:
O(1), as we only use a constant amount of extra space.
Method 2 - Using kind of prefix sum
A more optimal solution involves counting the contribution of each element to the final sum, based on its position.
Here is the approach:
- Calculate the contribution of each element to the sum of all odd-length subarrays:
- For each element at index
i, calculate how many subarrays of odd lengths include this element. - The contribution is given by the number of such subarrays multiplied by the element’s value.
- For each element at index
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n), This is because we are only iterating through the array once to calculate the contributions of each element. - 🧺 Space complexity:
O(1), as it uses a constant amount of additional space.