1588. Sum of All Odd Length Subarrays
Description
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.
Example 1:
Input: arr = [1,4,2,5,3] Output: 58 Explanation: The odd-length subarrays of arr and their sums are: [1] = 1 [4] = 4 [2] = 2 [5] = 5 [3] = 3 [1,4,2] = 7 [4,2,5] = 11 [2,5,3] = 10 [1,4,2,5,3] = 15 If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58
Example 2:
Input: arr = [1,2] Output: 3 Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.
Example 3:
Input: arr = [10,11,12] Output: 66
Constraints:
1 <= arr.length <= 100
1 <= arr[i] <= 1000
Follow up:
Could you solve this problem in O(n) time complexity?
Solutions
Solution 1: Dynamic Programming
We define two arrays \(f\) and \(g\) of length \(n\), where \(f[i]\) represents the sum of subarrays ending at \(\textit{arr}[i]\) with odd lengths, and \(g[i]\) represents the sum of subarrays ending at \(\textit{arr}[i]\) with even lengths. Initially, \(f[0] = \textit{arr}[0]\), and \(g[0] = 0\). The answer is \(\sum_{i=0}^{n-1} f[i]\).
When \(i > 0\), consider how \(f[i]\) and \(g[i]\) transition:
For the state \(f[i]\), the element \(\textit{arr}[i]\) can form an odd-length subarray with the previous \(g[i-1]\). The number of such subarrays is \((i / 2) + 1\), so \(f[i] = g[i-1] + \textit{arr}[i] \times ((i / 2) + 1)\).
For the state \(g[i]\), when \(i = 0\), there are no even-length subarrays, so \(g[0] = 0\). When \(i > 0\), the element \(\textit{arr}[i]\) can form an even-length subarray with the previous \(f[i-1]\). The number of such subarrays is \((i + 1) / 2\), so \(g[i] = f[i-1] + \textit{arr}[i] \times ((i + 1) / 2)\).
The final answer is \(\sum_{i=0}^{n-1} f[i]\).
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the length of the array \(\textit{arr}\).
1 2 3 4 5 6 7 8 9 10 11 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Solution 2: Dynamic Programming (Space Optimization)
We notice that the values of \(f[i]\) and \(g[i]\) only depend on \(f[i - 1]\) and \(g[i - 1]\). Therefore, we can use two variables \(f\) and \(g\) to record the values of \(f[i - 1]\) and \(g[i - 1]\), respectively, thus optimizing the space complexity.
The time complexity is \(O(n)\), and the space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 5 6 7 8 9 10 11 |
|
1 2 3 4 5 6 7 8 9 10 11 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 9 10 11 |
|