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.
1using System;
2
3class Program {
4 static int SumOddLengthSubarrays(int[] arr) {
5 int totalSum = 0, n = arr.Length;
6 for (int start = 0; start < n; ++start) {
7 for (int end = start; end < n; ++end) {
8 if ((end - start + 1) % 2 != 0) {
9 for (int k = start; k <= end; ++k) {
10 totalSum += arr[k];
11 }
12 }
13 }
14 }
15 return totalSum;
16 }
17
18 static void Main() {
19 int[] arr = {1, 4, 2, 5, 3};
20 Console.WriteLine(SumOddLengthSubarrays(arr));
21 }
22}
Similar to the Java and C++ implementations, this C# code uses a series of nested loops to process the subarrays, checking for odd lengths and summing them accordingly.
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
This solution computes the contribution of each element to possible odd-length subarrays using a mathematical formula. For each element, calculate how many subarrays include the element, split this into odd/even counts, and then use that to determine its overall contribution to the sum.