Sponsored
Sponsored
The brute force approach involves iterating over every possible subarray, checking if its length is odd, and then summing its elements. This approach is straightforward but not optimal.
Time Complexity: O(n^3) where n is the number of elements in the array, due to triple nested loops.
Space Complexity: O(1), only a few extra variables are utilized.
1function sumOddLengthSubarrays(arr) {
2 let totalSum = 0;
3 const n = arr.length;
4 for (let start = 0; start < n; ++start) {
5 for (let end = start; end < n; ++end) {
6 if ((end - start + 1) % 2 !== 0) {
7 for (let k = start; k <= end; ++k) {
8 totalSum += arr[k];
9 }
10 }
11 }
12 }
13 return totalSum;
14}
15
16const arr = [1, 4, 2, 5, 3];
17console.log(sumOddLengthSubarrays(arr));
JavaScript captures the brute force approach as well through nested loops that access each subarray and compute their sums if lengths are odd.
The optimized approach calculates the contribution of each element to the final sum using a mathematical formula. For each element at index i
, calculate how many odd-length subarrays it can contribute to, then sum directly based on these contributions.
Time Complexity: O(n), much improved by calculating contributions directly.
Space Complexity: O(1), only a few extra integer variables.
1
class Program {
static int SumOddLengthSubarrays(int[] arr) {
int totalSum = 0;
int n = arr.Length;
for (int i = 0; i < n; i++) {
int leftCount = i + 1;
int rightCount = n - i;
int oddCount = (leftCount * rightCount + 1) / 2;
totalSum += oddCount * arr[i];
}
return totalSum;
}
static void Main() {
int[] arr = {1, 4, 2, 5, 3};
Console.WriteLine(SumOddLengthSubarrays(arr));
}
}
This C# solution similarly relies on counting how each element participates in possible subarrays, thus leveraging mathematical simplification for efficiency.