Given an array of positive integers arr
, calculate the sum of all possible odd-length subarrays.
A subarray is a contiguous subsequence of the array.
Return the sum of all odd-length subarrays of arr
.
arr = [1,4,2,5,3]
58
[1,4,2,5,3]
and their sums are:
arr = [1,2]
3
arr = [10,11,12]
66
1 <= arr.length <= 100
1 <= arr[i] <= 1000
def sumOddLengthSubarrays(arr):
total_sum = 0
n = len(arr)
for i in range(n):
current_sum = 0
for j in range(i, n):
current_sum += arr[j]
if (j - i) % 2 == 0: # Check for odd length
total_sum += current_sum
return total_sum
# Test Cases
print(sumOddLengthSubarrays([1,4,2,5,3])) # Expected output: 58
print(sumOddLengthSubarrays([1,2])) # Expected output: 3
print(sumOddLengthSubarrays([10,11,12])) # Expected output: 66
O(n^2)
due to the nested loops iterating over the array to form subarrays.O(1)
since only a few extra variables are used regardless of the input size.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?